Skip to navigation

Events and Callbacks

In the browser most code is event-driven and writing interactive applications in JavaScript is often about waiting for and reacting to events, to alter the behavior of the browser in some way. Events occur when the page loads, when user interacts (clicks, hovers, changes) and myriad other times, and can be triggered manually too.

To react to an event you listen for it and supply a function which will be called by the browser when the event occurs. This function is known as a callback.

Here’s a group of the things needed to listen for an event; the callback function, an element and the call to listen for an event:

var handleClick = function (event) {
    // do something!
var button = document.querySelector('#big-button');
button.addEventListener('click', handleClick);

addEventListener is a method found on all DOM elements. Here it’s being called on an element saved in the button variable. The first argument is a string - the name of the event to listen for. Here’s it’s click - that’s a click of the mouse or a tap of the finger. The second is the callback function - here it’s handleClick.

Data about a particular event is passed to the event callback. Take a look at handleClick, declared above. You can see its argument: event - it’s an object whose properties describe what occurred.

Here’s an example event you might see into a click event callback like handleClick. There are lots of properties giving you an idea of where the event occurred on the page (like pageX and offsetY) - these are slightly different because they depend on the reference point used to measure from. You can also see the target which is a reference to the node that was clicked.

    offsetX: 74,
    offsetY: 10,
    pageX: 154,
    pageY: 576,
    screenX: 154,
    screenY: 489,
    target: h2,
    timeStamp: 1363131952985,
    type: "click",
    x: 154,
    y: 395