jQuery to hide a DIV when the user clicks outside of container

- Html 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

Popular posts from this blog

PHP: Date Difference for PHP 5.2

HTML5 video loop src change on end play function

Custom OpenCart 2.3.0.2 theme