Skip to content

Instantly share code, notes, and snippets.

@larrybotha
Last active December 15, 2015 09:09
Show Gist options
  • Save larrybotha/5235988 to your computer and use it in GitHub Desktop.
Save larrybotha/5235988 to your computer and use it in GitHub Desktop.
A basic solution for toggling dropdown menus in a navigation with jQuery.
/*
* 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