I am trying to add an active class to my subnavigation using the waypoints jQuery. I am trying to avoid writing multiple functions to adhere to the DRY idea. The waypoints toggle the function based on their location in the markup. Any suggestions welcome.
Markup
<!-- top section -->
<!-- waypoint class-->
<a href="#" class="homeNavItem1"></a>
<!-- partial for the code -->
<?php include 'partials/homepage/topHero.php'; ?>
<!-- content section one events -->
<!-- waypoint2 class-->
<a href="#" class="homeNavItem2"></a>
<!-- partial for the code -->
<?php include 'partials/homepage/section1.php'; ?>
JavaScript/jQuery
Backwards way:
$('.homeNavItem1').waypoint(function(direction) {
$('.homeAnchor1').addClass("subActive");
$('.homeAnchor2').removeClass("subActive");
$('.homeAnchor3').removeClass("subActive");
$('.homeAnchor4').removeClass("subActive");
$('.homeAnchor5').removeClass("subActive");
});
Efficient code attempt:
function waypointItem(x, y, i) {
$('.homeNavItem' + x).waypoint(function(direction){
$('.homeAnchor' + y).addClass("subActive");
$('.homeAnchor' + i).removeClass("subActive");
});
}
for (i = 2; i <= 6; i ++){
waypointItem(1, 1, i);
console.log(i);
}
1 Answer 1
A common question,
@elclanrs is right that you probably want a common class for your home anchor tags unless you truly want to style them all differently.
Then you could simply turn off the current active anchor with
$('.homeAnchor.subActive').removeClass("subActive");
Otherwise, you could try and see if this works for you:
$('.subActive').removeClass("subActive");
That assumes that on the whole page you use subActive
only for your home anchors of course.
homeAnchor
, no numbers; then figure out how to make it work targeting elements by index. \$\endgroup\$