简体   繁体   中英

jQuery “show/hide div on click” and “click outside to hide” not working together

// I searched but no luck, so I start a new question :)

I have:

<a class="icon hide-text" id="btnNoti5" href="#">Notification</a>

I want that: When I click on this a , it will show/hide a div and when I click outside that div, if it is visible, it hides.

I use this code to show/hide. It works fine:

var divNotifi = $('#divNotifi');
$('#btnNoti5').click(function(e) 
{
    if (divNotifi.is(":visible"))
    {           
        divNotifi.hide();
    }
    else 
    {         
        divNotifi.show();
    }
}

But when I add this code to hide the div when user click outside, it actually works, but above code stopped working: First click, it show the div. Second click: Nothing happens. The div wasn't hidden as expected.

$(document).mouseup(function (e)
{
    var container = $("#divNotifi");
    if (container.has(e.target).length == 0)
    {
        container.hide();
    }
});

Please help me. Thank you very much.

$(document).on('click', function(e) {
    var elem = $(e.target).closest('#btnNoti5'),
        box  = $(e.target).closest('#divNotifi');

    if ( elem.length ) {          // the anchor was clicked
        e.preventDefault();       // prevent the default action
        $('#divNotifi').toggle(); // toggle visibility
    }else if (!box.length){       // the document, but not the anchor or the div
        $('#divNotifi').hide();   // was clicked, hide it !
    }
});

FIDDLE

Use the same event in order to stop its propagation

$(document).click(function (e)
{
    var container = $("#divNotifi");
    if (container.has(e.target).length === 0)
    {
        container.hide();
    }
});

$('#btnNoti5').click(function(e) 
{
    if (divNotifi.is(":visible"))
    {           
        divNotifi.hide();
    }
    else 
    {      
        divNotifi.show();
    }
    return false;
});

There is a trick i like to use for thing such as this.

in the jQuery library:

$('#div').addClass('Class-Name');

whenever it is shows - add a class named "show".

and than for checking if it shows:

if ($('#div').hasClass('Class-Name') )
{
     // some actions
}

the .hasClass() is also a part of the jQuery library. and the last function from the jQuery library is: .removeClass()

so what i am doing is:

when show - add class "show" on click - check if has class "show" and than remove class.

hope you will find your way of using my trick :)

it makes it very easy to do things when they are so graphic. not much would like my method - but i do, it keeps you away from the mess.

$("#btnNoti5").click(function(){
    $("#notify").show();
});

$("#notify").click(function(){
    $("#notify").hide();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM