DOM Enlightenment Book

by peroli

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<button>click to say hi</button>

JavaScript

var sayHi = function(){console.log('hi')};

//adding event listener using anonymous function
document.body.addEventListener('click',function(){console.log('dude');},false);

//adding event listener using function reference
document.querySelector('button').addEventListener('click',sayHi,false);

//attempt to remove both event listeners, but only the listener added with a functions reference is removed
document.querySelector('button').removeEventListener('click',sayHi,false);

//this of course does not work as the function passed to removeEventListener is new and different function
document.body.removeEventListener('click',function(){console.log('dude');},false);
                       
//clicking the div will still invoke the click event attached to the body element, this event was not removed