Tutorial :jQuery event delegation with non-trivial HTML markup?



Question:

I have two DIVs, first one has a link in it that contains the id of the second DIV in its HREF attribute (complete setup on jsbin).

I want to animate the second DIV when user clicks on the first - anywhere on the first. I also want to use event delegation because I'll have many such "DIV couples" on a page (and I'm using a JS snippet from this SO answer).

If user clicks on the DIV itself, it will work - just check firebug console output. The problem is, if user clicks on one of the SPANs or the link itself, it doesn't work anymore.

How can I generalize the click handler to manage clicks on anything inside my DIV?

Here's the JS:

$('#a').click(function(e) {       var n = $(e.target)[0];       console.log(n);         if ( n && (n.nodeName.toUpperCase() == 'DIV') ) {           var id = $(n).find('a').attr('hash');             console.log(id);           $(id).slideToggle();       }       return false;   });   


Solution:1

It took me so long to write up the question that I decided to post it anyway, perhaps someone suggests a better way.

Here's the solution I found (jsbin sandbox):

$('#a').click(function(e) {      var n = $(e.target)[0];        var name = n.nodeName.toLowerCase() + '.' + n.className.toLowerCase();        if (n && (name === "div.clicker" || $(n).parents("div.clicker").length )) {          var id = $(n).find('a').attr('hash');          if(!id) {              id = $(n).parents("div.clicker").find('a').attr('hash');          }          console.log(id);      }      return false;  });  


Solution:2

Here is my solution. Not sure if that's exactly what you wanted, but it works for me.

$(document).ready(function() {      $('#a').click(function() {          var a = $("a", this);          $(a[0].hash).slideToggle();      });  });  

Edit: Tested in both IE7 and Fx3


Edit: In that case...

$(function() {      $("a.tab").click(function() {          $($(this).attr("hash")).slideToggle();          return false;      });  });  

Something like that might work (putting the tab class on anything that has a div "attached" to it). However, I'm not sure unless I actually see an example of it. Although if you want it to work when clicking on the span...you would attach the class to the span, and instead do:

$(function() {      $("span.tab").click(function() {          var a = $("a",this);          $(a.attr("hash")).slideToggle();      });  });  

Not sure if you want an open div to close if another one is opened. If this doesn't solve your problem, it would help if you would put up an example on jsbin...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »