Reputation: 295
I have a dropdown dropdown using ul and li:
<img class="options_toggle" src="assets/down_arrow.png"onclick="toggle_display('options');"/>
<ul id="options" class="options_content hide">
<li>
option one
</li>
</ul>
the options_toggle function swaps back and forth between the "hide" and "show" class in the options ul. Now I want to only hide it when the user clicks anywhere except the options toggle:
$(document).ready(function () {
document.onclick = function(e) {
// prevent the dropdown from closing instantly when you click the toggle to open it
$(".options_toggle").click(function (e) {
e.stopPropagation();
});
// hide the dropdown
$(".options_content").removeClass("show");
$(".options_content").addClass("hide");
};
});
But the problem is that the first time they load the page they have to click somewhere once before clicking the toggle. After the first click it works fine, they just have to click twice at first which can be annoying.
Any ideas what it's doing and why it cancels or ignores the first toggle? Thanks.
Upvotes: 0
Views: 58
Reputation: 780974
It's usually wrong to add an event handler inside another event handler. Just bind your $(".options_toggle").click()
handler at top-level.
$(document).ready(function() {
$(".options_toggle").click(function(e) {
// prevent the dropdown from closing instantly when you click the toggle to open it
e.stopPropagation();
});
$(document).click(function(e) {
// hide the dropdown
$(".options_content").removeClass("show");
$(".options_content").addClass("hide");
});
});
Upvotes: 1