Dennet
Dennet

Reputation: 23

jQuery on click SlideUp/Down script

I have created the following script:

$(".clickme").click(function () {
    var isVisible = $(".slide-div").is(":visible");
    $(".slide-div:visible").stop().slideUp(400);

    if (!isVisible) {
        $(".slide-div").slideDown(400);
    }           
});

The script works well, now I am trying to expand the script with a click outside the slide-div. So when I click outside the div it also slides up. I tried it with the following function, but that doesn't work.

$(":not(.slide-div)").click(function () {
    if ($(".slide-div").is(":visible");) {
        $(".slide-div:visible").stop().slideUp(400);
    }
});

Upvotes: 2

Views: 69

Answers (1)

Seika85
Seika85

Reputation: 2021

How about:

$(document).on('click', 'body', function (e) {

    var clicked_slideDiv = $(e.target).closest('.slide-div').length > 0,
        isClickme = $(e.target).is('.clickme'),
        isVisible = $(".slide-div").is(":visible");

    if(isVisible && (isClickme || !clicked_slideDiv)) { 
        $(".slide-div").stop().slideUp(400);
    } else if (!isVisible && isClickme) {
        $(".slide-div").slideDown(400);
    }
});

You can switch body with any selektor you want to narrow the "outside of the div" down to.

Upvotes: 1

Related Questions