-
-
Save jimboobrien/998d09ce6f17fad604ac82633cc94ae0 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment