swisstony
swisstony

Reputation: 1715

jQuery - click (almost!) anywhere to hide div

I have a search input box that appears upon rollover of a button. Rather than having its own close button I would like to be able to click anywhere on the page to re-hide the Search.

If I attach a click handler to the document this works fine but the problem being is that the search itself is part oofthe document. So if you click the input (which of course you need to do in order to type in a search) the search disappers.

I had hoped I'd be able to write a function soemthing like this...

$(document).not("#search").click(function(){ 
 $('#search_holder').fadeOut('fast'); 
});

i.e apply a click handler to the entire document APART from the search. Unfortunately that doesn't work.

so whats the answer?

thanking You in advance

Upvotes: 1

Views: 1475

Answers (3)

Hassan Sardar
Hassan Sardar

Reputation: 4523

Try this Its working perfect for me.

$(document).mouseup(function (e)
{
    var searchcontainer = $("#search_container");

    if (!searchcontainer.is(e.target) // if the target of the click isn't the container...
        && searchcontainer.has(e.target).length === 0) // ... nor a descendant of the container
    {
        searchcontainer.hide();
    }
});

Upvotes: 0

Ender
Ender

Reputation: 27283

Cancel the click event from propagating when it originates from the button you care about:

$("#search").click(function(event){ 
    event.stopPropagation();
});

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630637

You can do it by stopping the click event from bubbling, like this:

$(document).click(function() { 
  $('#search_holder').fadeOut('fast'); 
});
$("#search").click(function(e) {
  e.stopPropagation();
});

event.stopPropagation() prevents the bubble from going any higher, all the way to document triggering the .fadeOut(), everywhere else (by default) will bubble to document, causing the fade to occur.

Upvotes: 3

Related Questions