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 <li>
, <div>
and <ul>
.
$('li,div,ul').click(function () {
alert(this.id);
});
The problem is if I click on a <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?
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 <li>
, <div>
and <ul>
.
$('li,div,ul').click(function () {
alert(this.id);
});
The problem is if I click on a <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?
Share Improve this question edited Jan 23, 2020 at 10:06 ankitkanojia 3,1224 gold badges24 silver badges37 bronze badges asked Feb 25, 2009 at 4:52 user70687user706873 Answers
Reset to default 20You 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.