Event Delegation in jQuery

By Avinash

December 20, 2011Web Development4 Comments

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 relay for this while earlier version of jQuery use .delegate() form the version 1.7 this function is replaced by the .on().

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 .on() and .delegate().

  <div id="parent_ele">
    <a href="#" class="child">Link</a>
    <a href="#" class="child">Link</a>
    <a href="#" class="child">Link</a>
    <a href="#" class="child">Link</a>
    <a href="#" class="child">Link</a>
    <a href="#" class="child">Link</a>
  </div>
// 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'); });
  // 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');
  });

Share This Article

  • http://www.lototikrinimas.lt/ vikingu

    really nice tips!, thanx

  • Álvaro Carneiro

    But “delegate” function on jQuery works when you add other element into a website, for example.

    obj.on("a", "click", function(){ obj.append("Testing"); });
    obj.on("a", "click", function(){
        obj.append("<a href="#" rel="nofollow">Testing</a>");
      });

    This doesn’t works but if you use:

    obj.delegate("a", "click", function(){ obj.append("Testing"); });
    obj.delegate("a", "click", function(){
        obj.append("<a href="#" rel="nofollow">Testing</a>");
      });

    Works

  • David

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

    • http://www.xpertdeveloper.com Avinash

      Yes I am, updated thanks for noticing… :)