Reputation: 3941
I have a search input and I hid the submit button. Instead, when the user presses enter, a dropdown appears with the result using the following js:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(this).next("#searchResult").addClass('show');
return false;
} else {
return true;
}
});
});
How do I ensure that the class of .show
is removed if the user clicks outside of #searchResult
?
Upvotes: 2
Views: 6393
Reputation: 22711
Can you try this,
$("body:not(#searchResult)").click(function(){
$("#searchResult").removeClass("show");
});
Upvotes: 3
Reputation: 47966
You could utilize the blur
event to detect when an element looses focus:
$("#searchResult").on( "blur", function(){
// The users focus is no longer on this element!
});
You could also write this as:
$("#searchResult").blur( function(){
// The users focus is no longer on this element!
});
This of course is assuming that the #searchResult
element had the users focus to start with.
Reference:
Upvotes: 4