I have an if/else statement for our navigation where when a user clicks on the link associated with the dropdown-toggle
class a submenu pops up.
We have multiple links on our navigation with the dropdown-toggle
class. I only need to target 1 not all of them that's why I'm using .eq(0)
.
When the submenu appears a new class called open
gets injected to the parent <li>
.
For some reason I can't get this if/else
statement to fully work. I have the first half working but not the second.
For the else
portion I'm trying to add what would happen if the open
class got injected and the active-nav-tab
class gets added.
active-nav-tab
is the class used for the state when users are on the current page. active-nav-tab
is supposed to disappear when a user clicks on dropdown-toggle
of the current page only and when they click outside the window of the submenu. Then when a user clicks on a navigation link with dropdown-toggle
, the active-nav-tab
again is supposed to appear on the current page. Hopefully that makes sense. I've been at this for like two days.
Code Below:
$('.dropdown-toggle').click(function (e) {
if ($(this).not('open')) {
$('.dropdown-toggle').eq(0).removeClass('active-nav-tab');
alert('test1');
}
else {
$('.dropdown-toggle').eq(0).addClass('active-nav-tab');
alert('test2');
}
});
HTML
<li>
<a role="button">
<span ></span>
<span >Region</span>
</a>
</li>
<li >
<a role="button">
<span ></span>
<span >Region</span>
</a>
</li>
<li>
<a role="button">
<span ></span>
<span >Region</span>
</a>
</li>
I don't know what I'm exactly missing. Any help is gladly appreciated. Thanks!
CodePudding user response:
The quickest change you can make to your code to get the behavior you want is to replace
if ($(this).not('open')) {
With
if ($('.dropdown-toggle').eq(0).hasClass('active-nav-tab')) {
But without knowing your use case or how many "dropdown-toggle" elements you have it's hard to say if this would be a complete solution or not.
CodePudding user response:
this will process clicking on the first element with "dropdown-toggle" class
$('.dropdown-toggle:first').click(function () {
$(this).toggleClass("active-nav-tab");
if ($(this).hasClass("active-nav-tab")) {
alert ("Tab activated");
} else {
alert ("Tab deactivated");
}
}
also jQuery function not(selector)
should be used on enumeration of objects to filter it.
CodePudding user response:
This seems to have solved my issue more or less. I'll see what QA says lol Thank you!
$('.active-nav-tab').click(function (e) {
if ($(this).parents().hasClass("open")) {
$(this).addClass('active-nav-tab');
alert('activated');
}
else {
$(this).removeClass('active-nav-tab');
alert('deactivated');
}
});