Andrew Heins

default-image

Event Binding in Javascript


If you’ve recently picked up Javascript, you may have been quickly introduced to jQuery, mooTools or some other javascript framework that hides away many of the more rudamentary javascript functions that take place in a standard web application. While that’s convenient on the surface, it’s important to know how to do the same tasks without your framework of choice. You’ll never know when you’ll have to maintain an application that doesn’t make use of a framework, and even if that never happens, a javascript framework should never be a black box – to get the most out of it, you’ll want to get your hands dirty.

So, let’s dig a little. One of those rudamentary functions that frameworks can handle for your is event binding. Let’s look at how that’s done natively.

If you’ve ever used jQuery and you want to bind an event to clicking on a given link or element, you might do something like this:

$("myElement").click(function() {
  doStuff();
});

What does this do? It binds your function “doStuff” to the “click” event of your mouse. This syntax is convenient, but what’s really going on behind the scenes in native Javascript?

 

Inline Event Biding (aka The Old Way)

If you come from the old world of javascript or you’ve had the “pleasure” of working with some older websites or use some older code generators, you’ve probably seen something like this before:

< a onclick="doStuff()" href="#">Do Stuff!</ a>

This is an old and way to bind a function to a given event. It accomplishes the same thing as the jQuery code above, but it’s not very elegant because you’ve got javascript code riddled throughout your HTML, which can quickly turn into a maintanance nightmare. Thankfully there’s a more enlightened way to do this, but first we need to talk about the way HTML pages are structured.

 

The DOM

The DOM, or Document Object Model, is the structure that holds the HTML pages together. Every time you create a tag like <p> or <a>, you’re creating “nodes” in the DOM that various other languages can influence. Both CSS and Javascript interact with DOM nodes.

If you’re writing CSS and you write:

a { font-weight: bold; }

what you’re actually doing is telling the telling the browser to find all of the DOM <a> nodes and apply the relevant style information.

 

DOM Event Binding

Javascript can interact with the DOM the same way that CSS can, meaning you can keep your javascript out of your HTML and in a separate file.

Of course, like many things, Internet Explorer does things slightly different than the rest of the browsers, so you have to change the syntax slightly to make everything cross-browser compatible.

In Internet Explorer, the syntax is:

var el = document.getElementById("myElement");
el.attachEvent("onclick", doStuff);

and in Firefox, Chrome, Safari and all of the other browsers, the syntax is:

el.addEventListener("click", doStuff, false);

Not too bad… Let’s go over the parameters.

For all browsers, the first two parameters are pretty much the same.

(on)click” – This is the event you want to listen for. The verbs for events are exactly the same between IE and the other browsers, but Microsoft decided to add “on” in front, just to be clever.

doStuff – This is the function you want to call when the event actually happens.

The third parameter should simply be left as false. Mozilla has implemented the ability for addEventListener to trigger on “untrusted” events, but you shouldn’t have to worry about that. Just leave it as false.

 

Cross-Browser Compatibility

Instead of having to build two functions for each event, you can build your own little event binding function and use that instead of having to

Thankfully, you can build your own little function to do the :

function bindEvent(node, eventName, myFunction) {
  if (node.addEventListener) {
    node.addEventListener(eventName, myFunction, false);
  } else if (node.attachEvent) {
    node.attachEvent("on" + eventName, myFunction);
  }
}

source: http://stackoverflow.com/questions/1695376/msie-and-addeventlistener-problem-in-javascript

This way you’ve always got the right event binder for the browser.

 

One Last Issue – Passing Parameters

I’d be remiss if I didn’t mention that passing parameters doesn’t quite work using the syntax above.

If you try to pass the parameter “purple” to myFunction like so:

var el = document.getElementById("myElement");
bindEvent(el, myFunction("purple"));

you’ll get a javascript error. Javascript doesn’t like it when you pass parameters inside an event binder. Instead, you have to change your function call just a bit. While the above example won’t work, this will:

bindEvent(el, function() { myFunction("purple") });

This way you can appropriately pass parameters to a function that’s called in an event binding.

And that’s it! While you’ll probably still use your framework of choice for doing this kind of work, it’s always good to know what’s going on in the background and why.

If you’ve got any questions or comments, you can leave a comment below or follow me on Twitter.


Join the Conversation!