Last active
December 15, 2015 09:09
-
-
Save larrybotha/5235988 to your computer and use it in GitHub Desktop.
A basic solution for toggling dropdown menus in a navigation with jQuery.
This file contains 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
/* | |
* HTML: | |
* <ul class="menu"> | |
* <li> | |
* <a data-trigger="menu-1" class="http://yourlink.com">Link text</a> | |
* <ul data-target="menu-1"> | |
* ... | |
* </ul> | |
* </li> | |
* </ul> | |
*/ | |
(function(window, $) { | |
function Toggle () { | |
var $toggleValue = $('.menu a').data('trigger'), | |
$toggleTrigger = $('[data-trigger="' + $toggleValue +'"]'), | |
$toggleTarget = $('[data-target="' + $toggleValue +'"]').hide(), | |
$body = $('body'), | |
delay = 100, | |
isOpen = false; | |
function showTarget( $el ) { | |
$toggleTarget.slideDown(delay); | |
$el.addClass('open'); | |
isOpen = true; | |
$body.off( 'click' ).on( 'click', function( e ) { | |
hideTarget( $el ); | |
}); | |
} | |
function hideTarget( $el ) { | |
$toggleTarget.slideUp(delay); | |
$el.removeClass('open'); | |
isOpen = false; | |
} | |
$toggleTrigger.on('click', function ( e ) { | |
e.preventDefault(); | |
e.stopPropagation(); | |
$this = $(this); | |
if (!isOpen) { showTarget( $this );} | |
else { hideTarget( $this );} | |
}); | |
} | |
var toggle = new Toggle(); | |
}(this, jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment