Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Last active September 20, 2017 23:27
Show Gist options
  • Save wpscholar/5272794 to your computer and use it in GitHub Desktop.
Save wpscholar/5272794 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.
(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