Friday, April 8, 2011

Is it possible to have jQuery.click trigger on the top element only?

I'm trying to make a site where the user can click on any element to edit it's css. I use the following to add the click function to all lis, divs and uls.

$('li,div,ul').click(function () {  

alert(this.id); 

});

The problem is if I click on an li element, then I get the alert for that, and any element underneath it. (all the containers).

Is it possible to have only the top element trigger when clicked?

From stackoverflow
  • You want to stop event propagation, you do this in jQuery by calling the stopPropagation method on the event object.

    $('li,div,ul').click(function (e) {  
        e.stopPropagation();
        alert(this.id); 
    });
    
  • I believe you'd want to use stopPropagation(); inside the click function.

  • It sounds to me like you're looking for .stopPropagation(). Calling stopPropagation will prevent the event from "bubbling" up to parent containers.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.