jimboobrien
9/20/2017 - 11:27 PM

A jQuery plugin that will toggle the display of an element when another element is clicked. When the toggled element is being displayed, cli

A jQuery plugin that will toggle the display of an element when another element is clicked. When the toggled element is being displayed, clicking on the initiating element or any other element that is not the toggled element or its children will cause the toggled element to be hidden. Works on touchscreens.

(function( $ ) {

    /**
     * A jQuery plugin that will toggle the display of an element when another element is clicked.
     * When the toggled element is being displayed, clicking on the initiating element or any other element that
     * is not the toggled element or its children will cause the toggled element to be hidden.
     *
     * @param $el
     * @returns {*}
     */
    $.fn.toggleElement = function( $el ) {

        return this.each( function() {

            var $this = $(this);

            $this.data( 'toggleElement.active', false );

            var canTouch = 'ontouchstart' in document.documentElement;
            var event = canTouch ? 'touchstart.toggleElement' : 'click.toggleElement';

            $(document).bind( event, function(e) {
                var $clicked = $(e.target);
                if( $this.data('toggleElement.active') ) {
                    if( 
                        ! $clicked.is($this) && 
                        ! $.contains( $this.get(0), $clicked.get(0) ) && 
                        ! $clicked.is($el) && 
                        ! $.contains( $el.get(0), $clicked.get(0) ) 
                    ) {
                        $this.data('toggleElement.active', false);
                        $el.hide();
                    }
                }
            } );

            $this.bind( event, function(e) {
                e.preventDefault();
                $el.toggle();
                $this.data( 'toggleElement.active', $el.is(':visible') );
            } );

        } );

    };

})( jQuery );