简体   繁体   中英

jquery slide down div on link click, then slide up when clicking outside of div

Anyone know how I can have a link which when clicked slides down a div, then the div slides back up when anywhere outside the div is clicked ?

Thnx in advance.

Scott.

Try this:

$(".clicker").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    // do your worst, i.e. slide down
    $("div").slideDown("slow");
});

$(document).click(function() {
    // slide up
    $("div").slideUp("slow");
});

And just to make sure the div is not affected either:

$("div").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
});

Try this:

$(".target").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(".class").toggle();
});

Found a very good answer by Frederik in Document click not in elements jQuery

Modified a bit to support elements not yet present in document for example elements fetched by ajax calls.

$(document).on('click',function(event) {
    if (!$(event.target).closest("#selector").length) {
        if ($('#selector').is(":visible"))
            $('#selector').slideUp();
    }
});

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