Monday, November 28, 2011

Events in JavaScript

Events are the core of JavaScript. You use events to make the interaction between the DOM and the JavaScript. 

Event capturing and Event bubbling

Following diagram extracted from guistuff shows what is event capturing and bubbling are.



Example1 - Using pure JavaScript - return false and event.stopPropogation

        var outer = document.getElementById('outer'), //Outer element
            inner = document.getElementById('inner'); //Inner element

        outer.addEventListener('click', function (event) {
            console.log('outer');
        });

        inner.addEventListener('click', function () {
            console.log('inner');

            //Without anything outer will get fired

            //event.stopPropagation(); //outer won't get fired

            //return false; //Doesn't do anything.
        });

- When you use return false, it won't stop event from bubbling up.
- See this google search,  this, this or this for more information.

Event.preventDefault vs return false
You can use either of above return statements to prevent other event handlers from executing after a certain event. 

http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false

document ready functions
window.load vs document.ready


Sources
http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing
http://www.quirksmode.org/js/events_order.html
http://www.quirksmode.org/js/support.html
http://stackoverflow.com/questions/tagged/javascript-events
Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook