Skip to content

Commit 2116d14

Browse files
author
James Halliday
committed
events for lists
1 parent b869d1e commit 2116d14

File tree

3 files changed

+75
-4
lines changed

3 files changed

+75
-4
lines changed

dom.markdown

+48
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,54 @@ form.addEventListener('submit', function (ev) {
379379
});
380380
```
381381

382+
---
383+
# registering events for multiple elements
384+
385+
Suppose we have some html:
386+
387+
``` html
388+
<ul>
389+
<li>one</li>
390+
<li>two</li>
391+
<li>three</li>
392+
</ul>
393+
```
394+
395+
There are two ways we can register a "click" event for each
396+
`li` element.
397+
398+
---
399+
# register a listener on each element
400+
401+
We can register a "click" listener on each element:
402+
403+
``` js
404+
var items = document.querySelectorAll('ul li');
405+
for (var i = 0; i < items.length; i++) (function (elem) {
406+
elem.addEventListener('click', function (ev) {
407+
ev.target.style.fontWeight = 'bold';
408+
});
409+
})(items[i]);
410+
```
411+
412+
This is kind of messy. We need to use a closure because the
413+
for loop modifies the `i` index before the events fire so it
414+
is always the last index.
415+
416+
---
417+
# ev.target
418+
419+
A simpler way to register a listener for many elements is to
420+
register a listener on the parent `ul` and check the
421+
`ev.target`:
422+
423+
``` js
424+
var ul = document.querySelector('ul');
425+
ul.addEventListener('click', function (ev) {
426+
ev.target.style.fontWeight = 'bold';
427+
});
428+
```
429+
382430
---
383431
# xhr
384432

dom/list.html

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<html>
2+
<body>
3+
<ul>
4+
<li class="zero">zero</li>
5+
<li class="one">one</li>
6+
<li class="three">three</li>
7+
</ul>
8+
<script>
9+
var ul = document.querySelector('ul');
10+
ul.addEventListener('click', function (ev) {
11+
ev.target.style.fontWeight = 'bold';
12+
});
13+
</script>
14+
</body>
15+
</html>

dom/wow.html

+12-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
<html>
22
<head><title>wow</title></head>
33
<body>
4-
<h1 id="top">very tree</h1>
5-
<div class="msg">
6-
so <span>tall</span>
7-
</div>
4+
<form method="POST" action="/submit">
5+
<input type="text" name="cool">
6+
<input type="submit" value="submit this form!">
7+
</form>
8+
<script>
9+
var form = document.querySelector('form');
10+
form.addEventListener('submit', function (ev) {
11+
ev.preventDefault();
12+
var cool = form.querySelector('[name="cool"]');
13+
console.log(cool.value);
14+
});
15+
</script>
816
</body>
917
</html>

0 commit comments

Comments
 (0)