Задать вопрос
Ответы пользователя по тегу JavaScript
  • Как закрыть меню (slideToggle) по клику вне его?

    /**
     * Fires callback when user clicks outside element
     */
    (function ($) {
        var handlersCache = [];
    
        // setter
        $.fn.__doWhenClickOutside = function (callback, remove_after_exec) {
    
            // define vars
            var $this = $(this);
            remove_after_exec = (typeof remove_after_exec != 'undefined') ? remove_after_exec : true;
    
            // add new callback to a storage
            handlersCache.push({
                elem  : $this,
                cb    : callback,
                remove: remove_after_exec
            });
    
            return $this;
        };
    
        // trigger
        $(document).on('click.wph-outside', function (e) {
    
            var $target = $(e.target);
            if (handlersCache.length <= 0) {
                return;
            }
    
            $(handlersCache).each(function (index, handler) {
                if ($target.closest(handler.elem).length !== 0 || $target.is(handler.elem)) {
                    return;
                }
    
                handler.cb.apply(handler.elem);
    
                if (handler.remove) {
                    handlersCache.splice(index, 1);
                }
            });
    
        });
    })(jQuery);


    Использовать так:
    $('#menu-icon').__doWhenClickOutside(function() {
      // вызывается когда произошел клик вне меню
      $('#nav').slideUp();
      $(this).removeClass('active');
    }, false);
    
    // если второй параметр равен true, то коллбэк исполнится один раз и далее удалится
    Ответ написан