Behind the Library: Javascript Events

Javascript is becoming much more accessible thanks to libraries such as jQuery & Mootools. In this article, hopefully to form part of a new series, we are going to take a look behind the libraries – not looking at the code of the libraries but revealing how much easier they make our lives.

Adding Events – Easy with Libraries!

Today we’re going to be looking at adding events. With jQuery, it’s as simple as:


$('#header').click(function() {...});

However with normal javascript it’s not so nice. As you might expect, Firefox, Safari, Chrome, Opera and similar use one set (the correct, I might add) way of doing it, whereas Internet Explorer (all of them!) use a different code. That means for each event we add, we need to write the code twice. No worries though. I’m going to show you both sets of code and then we’ll create our own function to abstract the code away and let us write one set of code which will work with every browser.

Events without the Library

Firstly, we’ll set up just a simple function which we will run when an element is clicked.


function doSomething()
 {
 alert('you clicked me!');
 }

And an element for us to select:

<h1 id=&quot;header&quot;>This is what we'll be clicking on!</h1>

Select the Element for Clicking!

So our first step (and this works in all browsers, thankfully!)  we will just select the header element:


var h1 = document.getElementById('header');

Firefox, Safari, Opera, Chrome and so on.

So this is the code that all popular, modern day browsers use. It’s incredibly straight forward and is called addEventListener():


h1.addEventListener('click', doSomething, false);

The function takes 3 arguments. The first is the event – when you want the function to be run. We’ve used click, but there are countless others. The second is the function itself – we created this function earlier. Note that because we are passing the function through as an argument we don’t need to add brackets. The third is to do with javascript bubbling and when the event is fired. This is something which is a bit too complex right now, but we’ll cover it in the future!

Internet Explorer

IE’s code is pretty similar – oh Microsoft, why not just use the same as everyone else?


h1.attachEvent('onclick', doSomething);
 

This only takes two arguments, the event and the function to execute. Whereas with most browsers you would use ‘click’, this time it’s ‘onclick’. Simply put, add ‘on’ to any event.

If you run the respective code in the relevant browser, it will work. If you use the wrong code, check, and it wont work.

Our own Version.

So, this is a pain right? What we are going to do now is create our own function which will allow us to only write the addEvent code once, not twice. I’ll show you all the code and using the comments you should be able to see most of what is going on:


function addEvent(elem, evt, func, cap)
 {

 if(elem.attachEvent)
 {
 //if this evaluates to true, we are working with IE so we use IE's code.
 elem.attachEvent('on'+evt, func);
 } else {
 //the statement has evaluated to false, so we are not in IE/
 //the capture argument is optional. If it's left out, we set it to false:
 if(!cap) cap = false;
 //and use the normal code to add our event.
 elem.addEventListener(evt, func, cap);
 }
 }

And the usage of this is straight forward:


addEvent(h1, 'click', doSomething, false);

And We are Done

I hope you enjoyed this, it’s always good to step back from the library and write some of our own functions.

7 Comments on "Behind the Library: Javascript Events"

  1. Jason says:

    I really enjoyed this tutorial, great stuff.

  2. Vadim says:

    Of course it is good to know, but a library makes our lives easier.

  3. Rilwis says:

    Good article. But it looks like another article on Nettuts+. Anyway, thank you for this.

  4. Joseph says:

    That’s a cool code snippet there. Just one question: Does javascript allow for parameters to have default values? If so, could you just set cap with a default value to false?

  5. logolitic says:

    very interesting post and useful information

  6. Jurius says:

    What about custom events in ie? In firefox for example you can fire custom event by creating it with document.createEvent(), but in ie firing custom event causes an error.
    This code:
    var evObject = document.createEventObject();
    someelement.attachEvent(‘blowanevent’, function(){});
    someelement.fireEvent(‘blowanevent’);
    doesn`t work.

  7. Harry says:

    Photoshopped Image Killer is very useful to get detailed information of a JPEG image as for whether it has been Photoshopped. PSKiller opens and decodes your JPEG file, then several image statistics features are analyzed to see whether some of them are abnormal compared to those of untouched images.

Got something to say? Go for it!