Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Implement MooTools’ Elements.addEvent in jQuery

10 Responses »

One thing that I've always disliked about the jQuery JavaScript framework is its syntax for adding event listeners to elements. The way to add a click event to an element using jQuery is:

$('#myElement').click(function() {
	//do work
});

I love OOP so the above code tells me that a click is being triggered, not that it's going to add a listener to the element. There's nothing wrong with jQuery using that syntax; I simply don't prefer it. What I do when I need to work with jQuery is Moo-ify its syntax when I can. Here's how you can implement MooTools' "addEvent" syntax in MooTools.

The jQuery JavaScript

jQuery.fn.addEvent = jQuery.fn.bind; //updated

We add the "addEvent" function to the jQuery.fn object. Pretty simple.

The Usage

$(document).ready(function() {
	$('#myElement').addEvent('click',function(){ alert('w00t'); });
});

Looks a lot like MooTools, no? If you like jQuery's syntax of .click() type events, read my post: Implementing jQuery-Like Event Syntax in MooTools

Discussion

  1. August 7, 2009 @ 8:01 am

    More concise :

    jQuery.fn.addEvent = jQuery.fn.bind;

  2. August 7, 2009 @ 8:06 am

    Well put Pierre…well put.

  3. August 8, 2009 @ 2:12 pm

    I too prefer verbs like el.setStyle v. el.css. But swapping syntax would totally goof me up!

  4. August 8, 2009 @ 9:46 pm

    I don’t get it, why not just use


    $('#myelement').bind('click', function() {...});

    It’s even shorter than ‘addEvent’

  5. August 10, 2009 @ 6:22 am

    I agree with Corey, $().bind is exactly what you’re looking for…

  6. bo hunter
    December 9, 2009 @ 8:59 pm

    I would have to agree, this is nothing more than an alias.

  7. March 12, 2010 @ 12:31 am

    Mysteriously enough in jQuery version 1.4 I get this:

    $(“#website_stock”).addEvent is not a function

    When I set it as just click(fn) it works in Firefox, but not in IE8. It doesn’t return any errors – just the functions do NOT run whatsoever. Same with the bind() option – works in FF on mac, not on IE8.

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!