HTML and CSS Reference
In-Depth Information
You can see in the console that the
code now runs as expected. Notice
that a function is being passed as an
argument, as discussed earlier.
Now let's extend this example to add a button element and then add a
click handler to the element. The following screenshots show the page
before and after clicking the button.
This is the code to put in the events.js file:
Called on
button click
function add_element() {
var d = document.getElementById('second');
var p = document.createElement('p');
var t = document.createTextNode('Paragraph in the second div');
p.appendChild(t);
d.appendChild(p);
}
function go() {
var b = document.createElement('button');
var t = document.createTextNode('Click me');
b.appendChild(t);
b.addEventListener('click', add_element);
var d = document.getElementById('second');
d.appendChild(b);
}
window.addEventListener('load', go);
Same code you used
to modify the
document earlier
Creates button
and adds
event listener
Listens
to load
event
The final thing you need to be aware of is event bubbling . When an
event occurs, such as a click event, it bubbles up the document tree. This
 
Search WWH ::




Custom Search