How can i refactor my JS to use fewer if else statements and be less repetitive

You can use toggleClass instead of conditionally using addClass or removeClass: pass a second argument to indicate whether the class should be added or removed. This:

if (toTop >= 200 && toTop < 330 ) {
    // Adding class for second position
    jumpNav.addClass('pos2-carousel-subnav');
} else {
    jumpNav.removeClass('pos2-carousel-subnav');
}
// Behavior for side navigation (fixed) when page content scrolss
if (toTop >= 330 && distance > 380) {
    // Adding class for fixed position
    jumpNav.addClass('pos3-carousel-subnav');
} else {
    jumpNav.removeClass('pos3-carousel-subnav');
}
// Stop fixed position at footer
if (distance <= 380) {
    // Adding class for fadding out nav at footer position
    jumpNav.addClass('pos4-carousel-subnav');
} else {
    jumpNav.removeClass('pos4-carousel-subnav');
}

can be

jumpNav.toggleClass('pos2-carousel-subnav', toTop >= 200 && toTop < 330);
jumpNav.toggleClass('pos3-carousel-subnav', toTop >= 330 && distance > 380);
jumpNav.toggleClass('pos4-carousel-subnav', distance <= 380);

This same shortcut works with the native classList.toggle method as well as in jQuery with toggleClass.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top