n programming, an event is an action that occurs as a result of the user or another source, such as a mouse being clicked, or a key being pressed.
An event handler is a routine that is used to deal with the event, allowing a programmer to write code that will be executed when the event occurs.
When a function (bluify below) is used as an event handler, its this
is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener()
).
// When called as a listener, turns the related element blue
function bluify(e) {
// Always true
console.log(this === e.currentTarget);
// true when currentTarget and target are the same object
console.log(this === e.target);
this.style.backgroundColor = '#A5D9F3';
}
// Get a list of every element in the document
var elements = document.getElementsByTagName('*');
// Add bluify as a click listener so when the
// element is clicked on, it turns blue
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', bluify, false);
}