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;
}
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With