Reputation: 583
I have this function that adds or removes the navIsVisible class to a menu item. It allows a dropdown to appear. However, when I add two of those menu items and click one of them, the dropdown for both appears. I know this is because the two items share the same class and are identical, but how can I work around that without using ID's, because I'm trying to make the menu generation data-driven. Or how can I work around this in general? How can I get this function to only affect the trigger that I am clicking?
Toggle function:
function toggleNav(){
var navIsVisible = ( !$('.cd-dropdown').hasClass('dropdown-is-active') ) ? true : false;
$('.cd-dropdown').toggleClass('dropdown-is-active', navIsVisible);
$('.cd-dropdown-trigger').toggleClass('dropdown-is-active', navIsVisible);
if( !navIsVisible ) {
$('.cd-dropdown').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',function(){
$('.has-children ul').addClass('is-hidden');
$('.move-out').removeClass('move-out');
$('.is-active').removeClass('is-active');
});
}
}
Class being added:
$('.cd-dropdown-trigger').on('click', function(event){
event.preventDefault();
toggleNav();
});
I would really appreciate any help, thank you in advance!
Upvotes: 1
Views: 350
Reputation: 3435
when you capture the click, pass on the currentTarget
to your toggleNav function and use that to determine which div
to target:
$('.cd-dropdown-trigger').on('click', function(event){
event.preventDefault();
toggleNav(event.currentTarget);
});
Upvotes: 1
Reputation: 7783
Add the .first()
jQuery filter to your selector. More info at https://api.jquery.com/first/
$('.cd-dropdown').first().toggleClass('dropdown-is-active', navIsVisible);
Upvotes: 0
Reputation: 5292
Pass the click target as an argument to your toggleNav
function and toggle that instead of finding all the elements.
Upvotes: 1