Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  178] [ 4]  / answers: 1 / hits: 35820  / 12 Years ago, wed, december 12, 2012, 12:00:00

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;
}


More From » jquery

 Answers
25

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/


[#81480] Monday, December 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;