Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

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.

Solution 3:

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/

Solution 4:

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.

Solution 5:

Full answer demo is at: http://jsfiddle.net/leonxki/kSarp/

But here is a the jquery code snippet that mimics your requirements:

(functiontoggleSearchField() {
var$searchBoxDiv = $('#searchBoxContainer');

$(document).bind('click', function(evnt) {
    var$target = $(evnt.target);

    if ($target.is('#toggleSearchOn')) {
        $searchBoxDiv.fadeIn();
        return;
    } elseif ($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.

Post a Comment for "Jquery: How To Hide A Div When User Clicks On Anything But That Div. No Overlay"