Click outside > hide()
I have this jquery code:
$(document).ready(function(){
//global vars
var searchBoxes = $(".box");
var searchBox = $(".box");
var searchBoxDefault = "Search...";
searchBoxes.focus(function(e){
$(this).addClass("active");
$('#searchoptions').show();
});
searchBoxes.blur(function(e){
$(this).removeClass("active");
});
searchBox.focus(function(){
if($(this).attr("value") == searchBoxDefault) $(this).attr("value", "");
});
searchBox.blur(function(){
if($(this).attr("value") == "") $(this).attr("value", searchBoxDefault);
}); });
and html code:
<div id="search" class="right">
<form method="post" class="clearfix">
<input class="box left" type="text" value="Search..." />
<input class="button right" type="submit" value="" />
</form>
<div id="searchoptions">
Options:<br /><input checked="checked" type="radio"> Option1</label>
<input type="radio"> Option2</label>
<input type="rad开发者_运维百科io"> Option3</label>
</div>
</div>
The question is: How can I make when I click outside of #search id, to hide #searchoptions?
I tried with body click, but have bugs...and does not run perfectly...
Body click should will work perfectly. Only thing to do is to stop the event propagation. This should work...
$('body').click(function() {
$('#searchoptions').hide();
});
$('#searchoptions').click(function(event){
event.stopPropagation();
});
@see http://api.jquery.com/event.stopPropagation/
Well, since a click()
elsewhere on the page will effectively call the $(searchbox).blur()
event handler, you could just add something there to achieve your effect:
searchBox.blur(function(){
if($(this).attr("value") == "") {
$(this).attr("value", searchBoxDefault);
}
$('#searchoptions').hide();
});
JS Fiddle demo.
What you can do is bind a click event to the document that will hide the dropdown if something outside the dropdown is clicked, but won't hide it if something inside the dropdown is clicked
searchBoxes.focus(function(e){
$(this).addClass("active");
$('#searchoptions').show(function(){
$(document).bind('click', function (e) {
var clicked = $(e.target);
if (!clicked.parents().hasClass("class-of-dropdown-container")) {
$('#searchoptions').hide();
}
});
});
});
Then when hiding it, unbind the click event
$(document).unbind('click');
精彩评论