Do not run the second function if the first function is executed

I have a header with a drop-down, div, notification field ( #container) that switches to a slide. JavaScript for dropdown:

$("a.trigger").click(function (event) {
     $('#container').slideToggle(100)
     event.preventDefault();
});

I also have a function that closes the div field if I click anywhere outside #container:

$(document).mouseup(function (e) {
    var container = $('#container');

    if (!container.is(e.target)) {     
        container.hide();
    }
});

When I click on a.trigger, it lowers #container, and then if I click anywhere outside #container, it correctly closes it. But when I click a.trigger, while it is #containeralready open, it closes it from the second javascript function, as it a.triggeris outside #container, but then the first function starts too late and #containerslidestoggles down again immediately after hiding it.

Here is the fiddle: http://jsfiddle.net/Hx65Q/1013/

, , , javascript , . ? ?

+4
6

, .trigger ( ), if:

$(document).mouseup(function (e) {
    if($(e.target).closest('.trigger').length) return;
    var container = $('#container');

    if (!container.is(e.target)) {     
        container.hide();
    }
});

http://jsfiddle.net/Hx65Q/1034/


click , mouseup click . :

$("a.trigger").click(function (event) {
    $('#container').slideToggle(100)
    event.preventDefault();
    event.stopPropagation(); //Stop the event from bubbling
});

$(document).click(function (e) {
    var container = $('#container');

    if (!container.is(e.target)) {     
        container.hide();
    }
});

http://jsfiddle.net/Hx65Q/1036/

+4

event.stopPropagation() .

$("a.trigger").click(function (event) {
         $('#container').slideToggle(100)
         event.stopPropagation();
    });

$(document).click(function (e) {
        $('#container').hide();
    });

: $('# container'). slideUp (100);

+1

-?

var opened= false;

$("a.trigger").click(function (event) {
         $('#container').slideToggle(100)
         opened=!opened;
         event.preventDefault();
    });

$(document).mouseup(function (e) {
        var container = $('#container');

        if (!container.is(e.target) && !opened) {     
            container.hide();
        }
    });
0

.

if (!container.is(e.target)&&!$('a.trigger').is(e.target)) {     
        container.hide();
    }

: http://jsfiddle.net/Hx65Q/1031/

, , .

0

. e.target. , a.trigger e.target?

$(document).mouseup(function (e) {
        var container = $('#container');
        var trigger   = $('a.trigger');

        if (!container.is(e.target) && !trigger.is(e.target) ) {     
            container.hide();
        }
    });

http://jsfiddle.net/LMZX2/

0

,

$(document).mouseup(function (e) {
    var container = $('#container');      
    if (!container.is(e.target) && !$('.trigger').is(e.target)) {     
        container.hide();
    }
});

DEMO

0

Source: https://habr.com/ru/post/1548129/


All Articles