Jquery: How to hide a div when user clicks on anything BUT that div. No overlay
I'm thinking .one
would be of use in this situation? but i'm not sure how to do this...
I have a search box that appears when I click the search link. I want the user to be able to click on anything in that div without it closing, but when the user clicks on anythi开发者_StackOverflow中文版ng outside of that div, the div fades out.
Erm, here's an example that works on a div.
It uses a global var so I'm not proud, but it's fast to implement.
EDIT Updated my code, no global var now, it's still fast to implement.
Perhaps use the blur
event on the search box's input for that task?
$('div.search').find('input').blur(function() {
$('div.search').hide();
$('a#search').show();
});
$('a#search').click(function() {
var $a = $(this);
$a.hide();
$('div.search').show();
});
Something like this.
Use document as your click away. We also use stopPropagation()
on mydiv
so anything clicked that is not mydiv
will make it fadeout.
$('button, .mydiv').click(function(e) {
e.stopPropagation();
$('.mydiv').slideDown();
})
$(document).click(function() {
$('.mydiv').fadeOut();
})
See full example at http://jsfiddle.net/FWLF3/1/
I think this is your desired solution:
<div id="hi" style="height:100px; width:100px;border:1px solid #ddd"></div>
$('*',document.body).click(function(e){
e.stopPropagation();
var dom = $(this).get(0);
if($.trim(dom.id) != 'hi')
$('#hi').hide();})
thanks.
Full answer demo is at: http://jsfiddle.net/leonxki/kSarp/
But here is a the jquery code snippet that mimics your requirements:
(function toggleSearchField() {
var $searchBoxDiv = $('#searchBoxContainer');
$(document).bind('click', function(evnt) {
var $target = $(evnt.target);
if ($target.is('#toggleSearchOn')) {
$searchBoxDiv.fadeIn();
return;
} else if ($target.is('#searchBoxContainer') || $searchBoxDiv.has(evnt.target).length) {
return;
}
$searchBoxDiv.hide();
});})();
I tried to make the code as descriptive as possible to avoid commenting it, but let me know if you need annotation.
You should bind the click event on the document/body:
var thediv = $("#thediv.youwant");
// sluit resultaten met document click - niet wanneer op sayt-container wordt geklikt
$(document).click(function(e){
if(e.target.id != thediv.attr("id") && $(e.target).parents(thediv.selector).length == 0)
{
thediv.hide();
}
});
You'd have to tweak the $(e.target).parents(thediv.selector).length == 0) part a bit, it's still pretty specific for my case.
This piece of code checks (document onclick) if the target that is not is the div and not is an element within that div. And hides it.
精彩评论