Web Development

Event Delegation in jQuery

In one of the earlier article I have explained about Event Delegation in MooTools. So if you are not sure about the Event Delegation in JavaScript then you can refer this link.

Now in this article I am going to cover Event Delegation with jQuery.

MooTools uses [code]relay[/code] for this while earlier version of jQuery use [code].delegate()[/code] form the version 1.7 this function is replaced by the [code].on()[/code].

So now rather than explaining about Event Delegation, I will just explain the code in jQuery. Here you can find the example with both methods which are [code].on()[/code] and [code].delegate()[/code].

[cc lang=”html”]

[/cc]

[cc lang=”javascript”]

// Getting the object of parent Element
var obj = $(‘#parent_ele’);

// Here comes the Event Delegation

// For jquery below 1.7
obj.delegate(“a”, “click”, function(){
console.log(‘I am Clicked’);
});

// For jQuery 1.7 and above
obj.on(“a”, “click”, function(){
console.log(‘I am Clicked’);
});

[/cc]

Shares:
  • vikingu
    December 22, 2011 at 11:59 pm

    really nice tips!, thanx

    Reply
  • Álvaro Carneiro
    Álvaro Carneiro
    January 29, 2012 at 5:06 am

    But “delegate” function on jQuery works when you add other element into a website, for example.
    [cc lang=”javascript”]
    obj.on(“a”, “click”, function(){
    obj.append(“Testing“);
    });
    [/cc]
    This doesn’t works but if you use:
    [cc lang=”javascript”]
    obj.delegate(“a”, “click”, function(){
    obj.append(“Testing“);
    });
    [/cc]
    Works

    Reply
  • David
    David
    March 14, 2012 at 11:16 am

    I think you’re missing a ‘#’ here: var obj = $(‘parent_ele’); before parent, as you’re referencing the id “parent_ele”

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *