Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toggle- hide item when click outside of the div

I am using jquery's slidetoggle, want to learn how to make the showup class hide when click anywhere outside of the DIV. thanks!

Online SAMPLE: http://jsfiddle.net/evGd6/

<div class="click">click me</div>
<div class="showup">something I want to show</div>​
$(document).ready(function(){
    $('.click').click(function(){
        $(".showup").slideToggle("fast");
    });
});​
.showup {
    width: 100px;
    height: 100px; 
    background: red; 
    display:none;
}
.click {
    cursor: pointer;
}
    ​
like image 201
olo Avatar asked Dec 12 '12 00:12

olo


People also ask

How do I hide a div when clicked outside?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.

How can I show and hide div on mouse click using jQuery?

To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.


1 Answers

Stop event propagation from within the .showup area:

$(document).on("click", function () {
    $(".showup").hide();
});

Then prevent those clicks on .showup from bubbling up to the document:

$(".showup").on("click", function (event) {
    event.stopPropagation();
});

Any click event that reaches the document will result in the .showup element being hidden. Any click events that start from within .showup will be prevented from proceeding any further up the DOM tree, and thus will never reach the document.

You will also need to stop any clicks on your button from traveling up to the document as well:

$(".click").on("click", function (event) {
    event.stopPropagation();
    $(".showup").slideToggle("fast");
});

Otherwise that click event will bubble up to the document and result in the hiding of .showup immediately.

Demo: http://jsfiddle.net/evGd6/2/

like image 80
Sampson Avatar answered Sep 23 '22 09:09

Sampson