I have a menu that appears when I click an icon. Currently I can close it by clicking the 'close' icon, but I would like to be able to close it by clicking anywhere outside of the menu, when the menu is visible.
Here is a jsFiddle: http://jsfiddle.net/budapesti/3v5ym2bp/3/
For example the following doesn't work:
$(document).click(function() {
if($('.menu').is(":visible")) {
$('.menu').hide()
}
});
I found similar questions, such as jQuery: Hide element on click anywhere else apart of the element and How do I detect a click outside an element?, but couldn't get the solutions to work for me.
EDIT: I wonder if is(":visible") works with jQuery "animate"?
Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.
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.
$(document). click(function (event) { $('#myDIV:visible'). hide(); });
call close function on anywhere click on window. And use event bubbling. i had update it its jsfiddle link is
> http://jsfiddle.net/rahulrchaurasia/3v5ym2bp/19/
Try this : http://jsfiddle.net/3v5ym2bp/13/
html
<div class="inv"></div><!-- Added an invisible block -->
<div class="menu"> <span class="glyphicon glyphicon-remove closed pull-right"></span>
<ul>
<li>Link</li>
<li>Link</li>
<li>Link</li>
</ul>
</div>
<div class="icon-menu"> <span class="glyphicon glyphicon-menu-hamburger"></span>MENU</div>
css
.menu {
position: fixed;
width: 285px;
height: 100%;
left: -285px;
background: #202024;
z-index: 1;
}
.glyphicon-remove, ul {
color: #fff;
padding: 10px;
}
/* Added an invisible block */
.inv {
display:none;
width:100%;
height:100%;
position:fixed;
margin:0;
}
jQuery
"use strict";
var main = function () {
$('.icon-menu').click(function () {
$('.icon-menu').hide();
$('.inv').show(); //added
$('.menu').animate({
left: "0px"
}, 200);
});
//Added
$('.inv').click(function () {
$('.inv').hide();
$('.menu').animate({
left: "-285px"
}, 200);
$('.icon-menu').show();
});
$('.closed').click(function () {
$('.inv').hide();//added
$('.menu').animate({
left: "-285px"
}, 200);
$('.icon-menu').show();
});
};
$(document).ready(main);
Another simple example : http://jsfiddle.net/3v5ym2bp/17/
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