$('.searchbox').blur(function() {
$("#gohan").hide();
});
$('.dropdown').blur(function() {
$("#gohan").hide();
});
Hi, I have a searchbox that when I type in letters, a dropdown (id=gohan) consisting of a ul with numerous li “search results” appears. I want the dropdown to disappear whenever the focus on the dropdown or the searchbox is gone, ie they click on something that’s not in the searchbox/ul/li. Those two event handlers work fine separately, but I don’t know how to make them work together. I tried to string them together like
$('.dropdown, .searchbox').blur(function() {
but that resulted in catastrophic failure. Any idea on the condition/selector to fix this? I’ve also try to encapsulate both dropdown and the searchbox into one div containing them and selecting the big container, but that didn’t work either. If the searchbox isn’t out of focus, then there must be another check to see if the dropdown isn’t out of focus too. Only then, if both aren’t in focus, do the hiding. Is that the right logic?
It would be easier to hide your
#gohanif you just watched the document.body for clicks and focus and then inspected the target of the fired event. Essentially if the user clicks or focuses on something that is not within your ‘widget’ or set of ‘widget elements’ you hide your controls and let the user continue doing what they are doing.Depending on your DOM and the elements you are watching, you might also be able to do check the ancestors of the searchbox/dropdown and just check to see if the target element has a specific ancestor.
Example:
This would make it so that if your widget evolves to contain other controls, using those new controls will not hide the widget (as long as they are within the same ancestor, i.e. some parent div).