I have a div (id=”menu”) on my page with onclick=”toggledropdown()”. This div has child img elements as well as text. The toggle code works just fine when anything but the images is clicked. However, when the images are clicked, the div slides down and then back up again.
toggle code:
function toggledropdown()
{
if ($("#dropdown").is(":hidden"))
{
$("#dropdown").slideDown(400);
}
else
{
$("#dropdown").slideUp(50);
}
}
body.click to hide drop down if the page is clicked:
$(document.body).click(function(event)
{
var targetID = $(event.target).attr("id");
if (targetID !== "dropdown" && targetID !== "menu")
{
if (!$("#dropdown").is(":hidden"))
toggledropdown();
}
});
drop down.click to negate the body.click
$("#dropdown").click(function(e)
{
e.stopPropagation();
});
The html div (some things unrelated to problem omitted):
<div class="menu" id="menu" onclick="toggledropdown();">
<img id="dropdownthumbnail" (blahsrc/styleblah) />
Text
<img id="dropdownarrow" (blahsrc/styleblah) />
</div>
So, to reiterate, clicking on the menu div (minus the images) slides out the menu correctly, clicking on it again (including the images) or anywhere else on the page works correctly, but clicking on the images while the drop down is hidden toggles it twice (you can see it slide out and back in again).
Are the child imgs triggering the parent’s onclick twice? Once for the child, once for the parent? Why? How do I make it work as expected: clicking anywhere on the div triggers the onclick once?
You need to use event.stopPropagation to stop events from bubbling up.
Which will prevent parent handlers from firing their events