Can attach a JavaScript function (called an event listener or event handler) to a specific event and the browser will execute your function as soon the event occurs
Inline HTML Attributes
<div onclick="alert('Ouch!')">click</div>
Behind the scenes a function is still created and it contains the code you specified as a value of the onclick attribute
Element Properties
Assign a function to the onclick property of a DOM node element
<div id="my-div">click</div>
<script type="text/javascript">
var myelement = document.getElementById('my-div');
myelement.onclick = function() {
alert('Ouch!');
alert('And double ouch!');
}
</script>
Drawback that you can attach only one function to the event
DOM Event Listeners
You can have many functions listening to an event
When the event fires, all functions are executed
Example:
<p id="closer">final</p>
>>> var mypara = document.getElementById('my-div');
>>> mypara.addEventListener('click', function()
{alert('Boo!')}, false);
>>> mypara.addEventListener('click', console.log, false);
Removing Event Listeners
to remove the event listener, use removeEventListener()
If you remove a listener, you have to pass a pointer to the same function you previously attached.
So you cannot remove listeners that use anonymous functions.
>>> para.addEventListener('click', paraHandler, false);
>>> para.removeEventListener('click', paraHandler, false);
Capturing and Bubbling
third parameter in addEventListener
DOM Level 2 Events specification suggests that the events propagate in three phases
capturing
target
bubbling
Historically
- IE implemented only bubbling
- Netscape only capturing
- Firefox, Opera, and Safari implemented the three phases
You can stop the propagation of the event, in your listeners, so that it stops bubbling up and never reaches the document. To do this you can call the stopPropagation() method of the event object.
You can also use event delegation.
If you have ten buttons inside a <div>, you can always attach ten event listeners, one for each button. But a smarter thing to do is to attach only one listener to the wrapping <div> and when the event happens, check which button was the target of the click.
Prevent Default Behavior
// all links
var all_links = document.getElementsByTagName('a');
for (var i = 0; i < all_links.length; i++) { // loop all links
all_links[i].addEventListener('click', // event type
function(e) { // handler
if (!confirm('Are you sure you want to follow this link?')) {
e.preventDefault();
}
}, false); // don't use capturing
}
Not all events allow you to prevent the default behavior
can check the cancellable property of the event object.

No comments:
Post a Comment