Domanda

I am developing a responsive website. There are two functions: nested functions are used in both, handling event $(document).click(). Both hide the same elements — .dropdown.slide-out. However, in the first case, the function refers to the selector .dropdown, and in the second case to the selector .slide-out. The first works only: where am I going wrong?

/*
    |---------------------------------------
    | Dropdowns
    |---------------------------------------
    */
$(function () {
    var label = $('.dropdown-toggle');
    var allDropDowns = $('.dropdown-menu, .rmb-popup');
    var el = $(this);
    label.click(function () {
        if (Modernizr.mq('only screen and (min-width: 768px)')) {
            allDropDowns.hide();
            $(this).parents('.dropdown').children('.dropdown-menu').toggle('fast');
            label.removeClass('active');
            $(this).addClass('active');
            return false
        }
    });

    // Conflict point #1. Hide .dropdown.slide-out-right
    $(document).click(function () {
        allDropDowns.hide();
        label.removeClass('active');
    });

    allDropDowns.click(function (event) {
        event.stopPropagation();
    });
});
/*
    |---------------------------------------
    | Slide-outs
    |---------------------------------------
    */

$(function () {
    var soRight = $('.slide-out-right');
    $('.btn-menu-secd').click(function () {
        if (Modernizr.mq('only screen and (max-width: 767px)')) {
            soRight.animate({
                right: 0
            }, 400)
        }
        return false
    });

    // Conflict point #2. Slide out .dropdown.slide-out-right
    $(document).click(function () {
        if (Modernizr.mq('only screen and (max-width: 767px)')) {
            if (soRight.attr('style')) {
                soRight.animate({
                    right: '-270px'
                }, 400, function () {
                    soRight.removeAttr('style')
                })
            }
        }
    });

    soRight.click(function (event) {
        event.stopPropagation();
    });
});
È stato utile?

Soluzione

UPD: I was wrong. JQuery starts from 1.7 let to attach more than one or more handlers on 1 event. It will execute it in order of binding Documentation

FIDDLE

1:

$(function(){
var allDropDowns = $('.dropdown-menu');
$('.dropdown-toggle').click(function() {
        allDropDowns.show();
        return false;
});
$(document).click(function() {   
    allDropDowns.hide();
});    
$('.dropdown-menu').click(function(e) {
        e.stopPropagation(); 
        e.preventDefault(); 
});
});

2:

$(function() {
var slideOut = $('.slideout');
$('.btn-menu').click(function() {
        slideOut.show();
        return false;
});
$(document).click(function() {
    slideOut.hide();
});
$('.slideout').click(function(e) {
    e.stopPropagation(); 
    e.preventDefault();
});
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top