Trying to detect if a navigational element has a specific class upon click. If it has the class, remove it; if not, add it.
The goal is to display an active state on the dropdown button while the dropdown is open. The active state should be removed when another nav element is clicked or something outside the dropdown menu is clicked. This logic is currently working as intended.
However, there is an issue with removing the active state if the same button is clicked again. Currently, this functionality is not working. The first condition in the if statement never executes, causing the class to always toggle.
JS:
$(document).ready(function () {
//WORKS
$(document).click(function () {
$('.link.activeLink').removeClass('activeLink')
});
//WORKS
$('.nav-link').click(function () {
$('.link.activeLink').removeClass('activeLink')
});
//FAILS
$('.link').click(function () {
if ($(this).hasClass('activeLink')) {
$(this).removeClass('activeLink');
}
else {
$(this).toggleClass('activeLink');
}
});
});
CSS:
.activeLink {
background-color: #31A7DF;
}
HTML:
<a class="nav-link link dropdown-toggle text-white paddingRightButton h-100 noPaddingRightLeft" href="#" data-toggle="dropdown" id="flatRoofingDropdown" role="button" aria-haspopup="true" aria-expanded="false">
Flat Roofing
</a>