3
\$\begingroup\$

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);
}
asked Dec 4, 2014 at 20:50
\$\endgroup\$
1
  • \$\begingroup\$ Whenever you have incrementing numbers, it probably means you have to use a common class. So you want homeAnchor, no numbers; then figure out how to make it work targeting elements by index. \$\endgroup\$ Commented Dec 4, 2014 at 23:49

1 Answer 1

1
\$\begingroup\$

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.

answered Dec 5, 2014 at 15:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.