Saturday 26 March 2016

jQuery Hide Div when Clicked Outside or Anywhere

Hide Div using jQuery


Description:



In this example we explain that how to hide DIV when click outside the DIV tag using JQuery in asp.net or how to show or hide (close) Div when mouse is out or click outside using jQuery.
JQuery to Hide element when click anywhere in webpage using jQuery.

Sometime we have requirement like Hide popup when click outside the document using jQuery.
Below is the code to hide or close the element or popup if click outside using jQuery.

 Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>  Jquery to Hide Div element or popup when Click outside the Div using jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
try {
$(document).bind("contextmenu", function(e) {
e.preventDefault();
$("#menuitem").css({ top: e.pageY + "px", left: e.pageX + "px" }).show(100);
});
$(document).mouseup(function(e) {
var closediv = $("#menuitem");
if (closediv.has(e.target).length == 0) {
closediv.hide();
}
});
}
catch (err) {
alert(err);
}
});
</script>
<style type="text/css">
#menuitem
{
z-index: 1000;
position: absolute;
border: solid 2px black;
background-color: white;
padding: 5px 0;
display: none;
}
#menuitem ol
{
padding: 0;
margin: 0;
list-style-type: none;
min-width: 130px;
width: auto;
max-width: 200px;
font-family:Verdana;
font-size:12px;
}
#menuitem ol li
{
margin: 0;
display: block;
list-style: none;
padding: 5px 5px;
}
#menuitem ol li:hover
{
background-color: #efefef;
}


#menuitem ol li:active
{
color: White;
background-color: #000;
}

#menuitem ol .sublist
{
padding: 0px;
margin: 0px;
}

#menuitem ol .sublist hr
{
margin: 2px 0px;
}

#menuitem ol li a
{
color: Black;
text-decoration: none;
display: block;
padding: 0px 5px;
}
#menuitem ol li a:active
{
color: White;
}
</style>
</head>
<body>

<div id="menuitem">
<ol>
<li><a href="#">Forward</a> </li>
<li><a href="#">Reply</a> </li>
<li class="sublist">
<hr />
</li>
<li><a href="#">Delete</a> </li>
<li class="sublist">
<hr />
</li>
</ol>
</div>
Right click Anywhere in the page to show the custom popup menu. 
</body>
</html>


0 comments:

Post a Comment