Using jQuery to add or remove multiple classes at once

My navigation tabs use jQuery to add and remove classes for the active tab. However, I'm facing an issue where the active class is not removed when a new tab is clicked or when the user scrolls to a new section. Please refer to the following gist for more information: https://gist.github.com/flyspaceage/5720a4aa75815c20d6d703607f9d27c0

.active-break {
  background-color: #6390C6 !important;
}

.active-why {
  background-color: #6E8F82 !important;
}

.active-test {
  background-color: #E77C22 !important;
}

.active-deep {
  background-color: #466EA5 !important;
}
<ul class="pagination">
  <!-- <li>
    <a class="nav" href="#intro" class="nav-intro">
    Top
    </a>
    </li> -->
  <li>
    <a id="one" class="nav nav-break" href="#breaking-away">Breaking Away</a>
  </li>
  <li>
    <a id="two" class="nav nav-why" href="#why-right-now">Why Right OnCourse</a>
  </li>
  <li>
    <a id="three" class="nav nav-test" href="#testimonials">Testimonials</a>
  </li>
  <li>
    <a id="four" class="nav nav-deep" href="#deep-dive">Deep Dive</a>
  </li>
  <li>
    <a id="five" class="nav nav-resources" href="#resources">Resources</a>
  </li>
</ul>

/*
 * Scrollify
 **/
$(function(){
    $.scrollify({
        section: ".scrollify-section",
        interstitialSection : ".leaf .contact .footer",
        setHeights: false,
        touchScroll: false,

        before:function(i,panels) {
          var ref = panels[i].attr("data-section-name");

          $(".pagination .active").removeClass("active");

          $(".pagination").find("a[href=\"#" + ref + "\"]").addClass("active");

          var ref = panels[i].attr("data-section-name");

          if(ref==="breaking-away") {
            $(".breaking-away .carousel-box-shadow").addClass("animate");
          }
          if(ref==="intro") {
            $(".breaking-away .carousel-box-shadow").removeClass("animate");
          }
          if(ref==="testimonials") {
            $(".breaking-away .carousel-box-shadow").removeClass("animate");
          }
        },

        afterRender:function() {
          var pagination = "<ul class=\"pagination\">";
          var activeClass = "";
          $(".panel").each(function(i) {
            activeClass = "";
            if(i===0) {
              activeClass = "active";
            }
            pagination += "<li><a class=\"" + activeClass + "\" href=\"#" + $(this).attr("data-section-name") + "\"><span class=\"hover-text\">" + $(this).attr("data-section-name").charAt(0).toUpperCase() + $(this).attr("data-section-name").slice(1) + "</span></a></li>";
          });

          pagination += "</ul>";

        }
    });
});

/* Color active tab */

var selectorOne = '#one';

$(selectorOne).on('click', function(){
    $(selectorOne).removeClass('active-break');
    $(this).addClass('active-break');
});

var selectorTwo = '#two';

$(selectorTwo).on('click', function(){
    $(selectorTwo).removeClass('active-why');
    $(this).addClass('active-why');
});

var selectorThree = '#three';

$(selectorThree).on('click', function(){
    $(selectorThree).removeClass('active-test');
    $(this).addClass('active-test');
});

var selectorFour = '#four';

$(selectorFour).on('click', function(){
    $(selectorFour).removeClass('active-deep');
    $(this).addClass('active-deep');
});

Answer №1

The crucial piece of Javascript code is the last block. It is important to remove all classes from all items before adding the active class to the clicked item. This process must be done regardless of which item was clicked. The following solution should meet your needs:

$('#one').on('click', function(){
    $('.pagination a').removeClass();
    $(this).addClass('active-break');
});

$('#two').on('click', function(){
    $('.pagination a').removeClass();
    $(this).addClass('active-why');
});

$('#three').on('click', function(){
    $('.pagination a').removeClass();
    $(this).addClass('active-test');
});

$('#four').on('click', function(){
    $('.pagination a').removeClass();
    $(this).addClass('active-deep');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What precautions should I take to safeguard my HTML/CSS/JS projects when sharing a link with my employer?

Picture this scenario: you need to share a link for your work, but you want to protect it from being easily copied or developed further by someone else. However, since it's a document, any browser can still view it. Can anyone recommend a tool that wi ...

What is the best way to design distinct buttons for various devices?

For my current responsive web design project, I have utilized Bootstrap extensively. Recently, I encountered a new issue that I'm uncertain of how to tackle. The problem arises with the following HTML code snippet: <!-- button color depending on d ...

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...

Trouble getting proper alignment displayed with JavaScript and CSS

If anyone has a solution for printing content in a div using JavaScript and CSS, please help. The main div with the id 'preview' contains content taken from a database using PHP and MySQL. However, the data on the print page appears vertically an ...

Adjusting the size of the post title's font

Looking to decrease the font size of the latest post's title and keep it centered on my Jekyll based blog. I attempted to adjust https://github.com/x0v/x0v.github.io/blob/master/_sass/atoms/_feature-title.scss by adding font-size: 45px !important; f ...

After an ajax call in ASP .NET MVC3 using Razor, jQuery may not function properly

When I perform a post back to obtain a partial view using ajax, I utilize the following code to render the partial view within a div named 'DivSearchGrid'. <script type ="text/javascript" > $('#Retrieve').click(function ( ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

Learn how to create a visually stunning CSS menu by centering a background image from the website cssmenumaker

I found a ready-made dropdown menu on . The menu is working well, but I would like to center the buttons. Is there a way to do this? Here is the CSS code: @import url(http://fonts.googleapis.com/css?family=Open+Sans:600); /* Menu CSS */#cssmenu, #cssmenu ...

Align a div in the center with another div positioned to its left and floated

I am in the process of creating a footer with three components: a logo aligned to the left, a centered navigation menu, and a set of social icons on the right. I have encountered an issue where when I float the logo to the left, the list items within my na ...

Unable to locate template or render function for Vue Draggable Next component

Looking to incorporate Vue Draggable Next into a Vue 3 example page but encountering some challenges. I've attempted to follow the instructions in the repository. However, I ran into issues when importing the Vue Draggable Next component and had to re ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

Using Angular 2 to round a calculated number within HTML

In the HTML code, there is a calculated number associated with Component1. Component1 serves as a tab page within a Bootstrap tab panel. Below is the HTML code with the tab panel: <div id="minimal-tabs" style="padding:75px;padding-top:60 ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

Steps to make pop-up iframe function on the same page within a react nextjs application

My vanilla Html app has a pop-up feature that functions perfectly. When the button is clicked, the pop-up opens and everything works as expected. However, I am encountering an issue when trying to implement this same functionality in my React, NextJS app. ...

Tips for rearranging a span following an image?

Looking for a solution to rearrange a span element after an image within automatically generated HTML. Sample HTML: <span>closed</span> <img alt="Click to reset" src="xxx" class=""> Currently, the span appears before the img in the cod ...

Dynamic calendar with flexible pricing options displayed within each cell

I've been wracking my brain over this issue for quite some time now, but still can't seem to find a solution! Is there a React Calendar out there that allows for adding prices within the cells? I simply want to show a basic calendar where each c ...

Is the "sizes" attribute of the "picture" element functional in Chrome when it comes to <source>?

The incredible <picture> element has been functioning flawlessly in the Chrome browser for well over a year, yet regrettably, I seem to be encountering an obstacle when attempting to make use of the powerful sizes attribute within the <source> ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...