views:

466

answers:

3

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?

+6  A: 

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); 
});
Luca Matteis
+1  A: 

I believe you'd want to use stopPropagation(); inside the click function.

Alex JL
+1  A: 

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

Stuart Childs