How to prevent toggle on element within toggle area using jquery
I have a jquery toggle to show/hide a div tag using the h2 element in the code below. Within that h2 I have a clickable image (a context menu icon). The context menu works when clicking it, but the h2 also toggles the show/hide on the div. Is there a way you can cancel the toggle functionality on the icon within the h2 tag?
<h2>Title goes here<img src="context-menu.gif" /></h2>
<div class="panel"></div>
I have tried playing about with layering the icon on开发者_运维问答 top of the h2 tag, but this brings about other complex issues with my design. Also floating the two side by side isn't an option either.
Thanks.
Click events (which is essentially what toggle() binds to) bubble up the DOM, firing on all ancestors of the target element. Here, you need to stop the propagation/bubbling at the <img>
element using event.stopPropagation():
$("h2 > img").click(function (evt) {
// Stop the event from bubbling up and firing the h2's handler
evt.stopPropagation();
// Continue on with my code
showContextMenu();
});
精彩评论