Question

I have a div, and within that div, various elements (h3, p, span, a, etc.). I made the whole div clickable with jquery:

$(".play").click(function(){
   window.location=$(this).find("a.play-detail").attr("href"); 
   return false;
});

It all works fine. Except that i have 2 other links in the DIV and I can't access them anymore (the DIV-click takes over). Here's an exemple of the structure:

<div class="play">
  <h3>Title</h3>
  <a>One link</a> <!-- not working!! -->
  <a class="play-detail">Link for the whole div</a>
</div>

Thanks.

Was it helpful?

Solution

You can use e.stopPropagation():

$(".play").click(function(){
    window.location=$(this).find("a.play-detail").attr("href"); 
    return false;
});

$(".play a").click(function (e) {
    e.stopPropagation();
});

Fiddle Demo

OTHER TIPS

You can do this?

$(".play").click(function(e){
   if(e.target.nodeName != "A"){
     window.location=$(this).find("a.play-detail").attr("href"); 
     return false;
   }
});

What you are searching for is the event target, to check for this you first have to grab the event object that jquery provides. You can then check for the target:

$(".play").click(function(e){
   if(!$(e.target).is('a')){ //this checks if the clicked element was an a tag
      window.location=$(this).find("a.play-detail").attr("href"); 
      return false;
   }
});

Also I have to say it's a little weird to use links like that, but that's up to you.

You can pass the event object to the handler, and then use that to determine whether or not to run the code:

$('.play').click(function(event) {

   var $target = $(event.target); // this is the element which was clicked

   if ( $target.is('a') && !$target.hasClass('play-detail') ) {
     return; // don't execute any code beyond this point if the
             // target is an anchor without the 'play-detail' class
   }      

   event.preventDefault();
   window.location = $(this).find('a.play-detail').attr('href'); 


});

Here's a fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top