jQuery to hide a DIV when the user clicks outside of container
- Html code
- Css Code
- jQuery Code
<a href="#" class="select-link">Select List</a> <ul class="dropdown-menu-list"> <li><a href="#">My item name 1</a></li> <li><a href="#">My item name 2</a></li> <li><a href="#">My item name 3</a></li> <li><a href="#">My item name 4</a></li> </ul>
- Css Code
.dropdown-menu-list {display:none;}
- jQuery Code
$(".select-link").on('click',function(e) { e.preventDefault(); $(".dropdown-menu-list").show(); })
$(document).mouseup(function (e) { var container = $("YOUR CONTAINER SELECTOR"); if (!container.is(e.target) // if the target of the click isn't the container... && container.has(e.target).length === 0) // ... nor a descendant of the container { container.hide(); } });
Comments
Post a Comment