How do I prevent clicks from propagating from my delete button? I'm using Twitter Bootstrap 3 to display an image carousel, with the option to click and display the image full-size in a modal dialog, which is triggered by an onclick
on the slide div.
The problem is that I'm also trying to include a delete button inside the slide div, and the clicks are propagating from the delete button to the containing div- meaning that when you try to delete, it'll pop up the CakePHP "Are you sure?" message, and if you say no, the modal opens instead.
Why isn't stopPropagation()
working here?
<div class="item" onclick="$('show-image').modal('show');" style="background-image:url(blablabla);">
<div class="carousel-caption" onclick="function handler(event) {event.stopPropagation();}">
Image caption goes here
CakePHP framework Javascript delete button goes here (generated in PHP)
</div>
</div>
The reason that stopPropagation
wasn't working in your code is because onclick="function(e){}"
doesn't do anything, it just declares a function and tosses it away.
Here's what you want as a general solution:
<div class="parent" onclick="parentClicked();">
<div class="child" onclick="event.stopPropagation();childClicked();">
</div>
</div>
window.event
gets set to the current event being fired, in this case a MouseEvent
object.
Your onclick
isn't actually using the function you define within it. You can make it work (on IE9+ and other modern browsers) like this:
onclick="event.stopPropagation();"
Note that that isn't a function, it's the contents of a function.
DOM0 onXyz
handlers essentially boil down to this:
theElement.onclick = function(event) {
// ...your onclick content here
};
So you can see why your code wasn't working:
theElement.onclick = function(event) {
function handler(event) {event.stopPropagation();}
};
But as you're using jQuery, your better bet would be to not use onXyz
attributes at all, and instead hook up your handler in a modern way:
$(".carousel-caption").on("click", function(e) {
e.stopPropagation();
// do your thing here
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.