Reputation: 2530
I am styling a few MultiSelect elements with unordered (<ul>
) HTML lists and this function is meant to hide the element when a user clicks anywhere on the document other than 'dropdown_box' or 'dropdown_container'.
The function isn't working for anything within the <ul>
tags, and it's hiding the element as soon as soon as a list item is clicked. I've tried specifying both the id of the <div>
as well as the <ul>
and it still closes as soon as it's clicked.
UPDATE - I created a jsfiddle to demonstrate the problem http://jsfiddle.net/chayacooper/ezxSF/16/
There is a separate mouseleave function which closes the element for most uses, but I need to add this functionality in order to close the element if the user clicks to open it but doesn't mouse over any of the 'UL Element' items.
JS
$('html').click(function (e) {
if (e.target.id == 'dropdown_box' || e.target.id == 'dropdown_container') {
$("#select_colors").show();
} else {
$("#select_colors").hide();
}
});
HTML
<div id="dropdown_box">Select</div>
<div id="dropdown_container">
<ul id="select_colors">
<!-- Several List Item Elements -->
</ul>
</div>
Upvotes: 2
Views: 663
Reputation: 207900
Try this:
$('html').click(function () {
$("#select_colors").hide();
});
$('#dropdown_box, #dropdown_container').click(function (e) {
e.stopPropagation();
$("#select_colors").show();
});
Clicking on the html will hide the list, while clicking on #dropdown_box or #dropdown_container will show it and stop the event bubbling.
Upvotes: 2
Reputation: 13162
I would do this a different way. Attach a global click handler to "body" that hides the div, and attach a click handler to your dropdown_box and dropdown_container that stops the propagation of the event (by returning false and calling e.stopPropagation). This way the body event handler will never see the event.
$('html').click(function () {$('#select_colors').hide(); });
$('#dropdown_box, #dropdown_container').click(function (e) {
e.stopPropagation();
return false;
});
UPDATE changed body to html, and hid the "select_colors" instead of the dropdown_container.
Some references:
http://www.quirksmode.org/js/events_order.html
Event propagation in Javascript
Upvotes: 2