Monday, September 2, 2019

javascript - Hide a div when clicking on anything that is not the div




I have a div called .dots_menu that shows up when clicking on .dots.



I am trying to write a code that hides this div whenever a user clicks on anything else that is not the .dots_menu div (ex: the background of the page around the div).




This is my HTML part:







This is my CSS part:




.dots{
height: 25px;
float: right;
}

.dots_menu{
display: none;
width: 202px;
position: absolute;

top: 40px;
right: 1px;
z-index: 1;
background: rgb(238, 238, 238);
-webkit-box-shadow: 0px 4px 15px #000;
-moz-box-shadow: 0px 4px 15px #000;
box-shadow: 0px 4px 15px #000;
}

.dots_menu.show{

display: block;
}

.dots_menu a {
display: block;
text-decoration: none;
color: #000;
padding: 10px;
font-family: arial;
}



And this is my jQuery that doesn't work:



$('.dots').click(function(){
$('.dots_menu').removeClass('show');
$(this).next().addClass('show');
$(document).one("click",function(){ //
$('.dots_menu').removeClass('show');
});

});

Answer



off the top of my head:



$(document).click(function() {
if( ! $(this).hasClass('dots_menu') && $('.dots_menu').hasClass('show')) {
$('.dots_menu').removeClass('show');
}
});



EDIT: according to https://stackoverflow.com/a/7385673/2061557



$(document).mouseup(function (e)
{
var container = $(".dots_menu");

if ( ! container.is(e.target) && container.has(e.target).length === 0)
{

$(".dots_menu").removeClass("show");
}
});


You should also consider to use Twitter Bootstrap Modals http://getbootstrap.com/javascript/#modals


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...