I use show hide Slide toggle for hide my login panel. When I click on LogIn button it shows and when I again click in logIn button it hides, but I want that when I click on logIn button it show and when I click anywhere in body it hide automatically.
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showmenu').click(function() {
$('.login-wrapper').slideToggle();
});
});
</script>
I use show hide Slide toggle for hide my login panel. When I click on LogIn button it shows and when I again click in logIn button it hides, but I want that when I click on logIn button it show and when I click anywhere in body it hide automatically.
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showmenu').click(function() {
$('.login-wrapper').slideToggle();
});
});
</script>
Share
Improve this question
edited Mar 30, 2015 at 11:22
tutankhamun
9302 gold badges11 silver badges23 bronze badges
asked Mar 21, 2014 at 5:17
SamSam
373 silver badges8 bronze badges
2 Answers
Reset to default 4Have a click event bound to the document object
$(document).ready(function () {
$('#showmenu').click(function (e) {
$('.login-wrapper').stop(true).slideToggle();
});
$(document).click(function (e) {
if (!$(e.target).closest('#showmenu, .login-wrapper').length) {
$('.login-wrapper').stop(true).slideUp();
}
});
});
Demo: Fiddle
You can add a .click
handler to the document level to slide up the .login-wrapper
.
But when you use it like that then when .login-wrapper
is opened by clicking on the button #showmenu
, the click will be bubble up on the DOM tree and fire the click event at the document level as well which will close your .login-wrapper
again eventually.
That's why you need to make use of e.stopPropagation()
here to prevent bubble up the DOM tree so your .login-wrapper
will not be closed if you click on the button.
$(document).ready(function () {
$(document).click(function () {
$('.login-wrapper').slideUp();
});
$('#showmenu').click(function (e) {
e.stopPropagation();
$('.login-wrapper').slideToggle();
});
});
Fiddle Demo
Based on your ment, you can use:
$(document).ready(function () {
$(document).click(function () {
$('.login-wrapper').slideUp();
});
$('#showmenu').click(function (e) {
e.stopPropagation();
$('.login-wrapper').slideToggle();
});
$('.login-wrapper').click(function (e) {
e.stopPropagation();
});
});
Updated Fiddle