JavaScript event registering without using jQuery

The easiest way is:

// DOM Level 0 way
window.onload = function () {
  document.getElementById("someButton").onclick = function() {
    alert("Hello");
  };
};

This will work on all browsers but note that with this approach only one event handler can be attached to an event.

Also notice that the onload event is not completely equivalent to the jQuery’s ready event, onload will be fired when all the resources of the page are completely loaded (images, sub-frames, etc…), while ready fires as soon the DOM has been parsed.

If you want to attach multiple event handlers, you can use the DOM Level 2 Standard element.addEventListerner method (or element.attachEvent for IE)

The simplest abstraction to get a cross-browser way to bind events is:

function addEvent(el, eventType, handler) {
  if (el.addEventListener) { // DOM Level 2 browsers
    el.addEventListener(eventType, handler, false);
  } else if (el.attachEvent) { // IE <= 8
    el.attachEvent('on' + eventType, handler);
  } else { // ancient browsers
    el['on' + eventType] = handler;
  }
}

Then you can:

var button = document.getElementById("someButton");
addEvent(button, 'click', function () {
  alert("Hello");
});

addEvent(button, 'click', function () {
  alert("world!");
});

Be aware also that the addEventListener and the IE’s attachEvent methods have their differences, when you attach multiple handlers to an event with addEventListener they will be fired in the same order, as the handlers were bound (FIFO), attachEvent will trigger the handlers in the contrary order (LIFO).

Check an example here.

Leave a Comment