JavaScript Event Listeners

This page is marked as In Progress so expect small errors or unfinished bits

onmouseup() and onkeyup() may work most of the time but more complex scripts run up against some problems with them. To put it as simply as possible how do you handle events for a DIV when that DIV is inside another DIV which also has the same event trigger (e.g. onclick)? This could easily happen if you were creating a Web application. Should the script react because the inner DIV was clicked or should the click be handled by the outer DIV? Or both?

Event listeners

Event listeners do not work reliably yet but as browsers catch up to the new way of doing things you will want to start using them:

document.getElementById('fred').addEventListener('mouseup',calculateColour,false)        
        

addEventListener is a method for many objects on the Web page. It creates an event listener. In this case the event listener is looking for a mouse up event and when it "hears" one it triggers the function calculateColour(). The FALSE at the end refers to when the function will be triggered. For now just leave it as false as browsers have yet to get this bit right (even the ones which support event listeners). The theory is that if a user clicks on an object inside another object and both have listeners for the same event:

Event properties

As event listeners will be used on more complex pages you will probably need to use more of the JavaScript event properties which are available. For example, e.target will show which object was clicked on. This is useful if many objects call the same function. If objects on a page can be dragged and dropped you would want to know which was being dragged.

You can cancel an event listener at any time:

document.getElementById('fred').removeEventListener('mouseup',calculateColour,false)            
        

Default event handlers

Some objects have default event handlers (for example links (A elements)). To prevent these from being triggered after your function has handled the event you need to include this at the end of the function:

e.preventDefault()                
        
submit to reddit Delicious Tweet