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

Tips for expanding the width of an image when employing position:relative

Below is the code snippet: <table border="1" cellpadding="2" cellspacing="2" height="250"> <tbody> <tr> <td> <div style="background: url('path to image'); width: 300px; height: 250px; position: ...

Simple method for converting pixel values to em units

I'm searching for a simple method to incorporate a line of code into one of my plugins in order to convert specific pixel values into em values. My project's layout requires the use of ems, and I'd prefer not to rely on external plugins for ...

Sending both data and images concurrently through AJAX JSON in ASP.NET MVC involves several steps. You can achieve this by properly

Initially, my task was to create a form with data only for sending it to the action, without including any image. However, I am now facing a new requirement to send both data and an image via POST request to the action. It seems challenging as I am unsure ...

having difficulty placing 3 pop-up windows on a single page

Struggling to implement multiple popups on my page, each with a unique ID assigned. Any assistance would be greatly appreciated. Here is the code snippet: .fa { font-size: 50px; cursor: pointer; user-select: none; } .fa:hover { font-size:20px; t ...

What is the best way to display a Bootstrap alert above all other elements on the page?

I need help with adjusting the placement of my bootstrap alert. Currently, when the input box value is not valid and the button is clicked, the alert shows up below the input box. I would like it to appear in the middle of the page, on top of the text box. ...

Utilize JQuery to identify and select every parent element, then retrieve the height of the first child element and adjust the height of the

Recently, I developed a PHP script that pulls news and case posts from a database. The HTML structure used for displaying these posts is as follows: <a href='/post/placeholder'> <div class='col nopadding col12-12 counter'> ...

Turn the flipcard hover effect into an onclick action

After successfully creating interactive flip cards using CSS hover effects, I am now faced with the challenge of adapting them for mobile devices. I'm struggling to figure out how to translate my hover effects into onclick events for a mobile-friendl ...

Plugin for turning text into "leet speak" using jQuery and Javascript

Recently, I've been on the hunt for a 1337 translator that I can seamlessly integrate into a jQuery plugin. While I believe I'm making progress, I can't shake off the feeling that something's amiss. My gut tells me that what I currently ...

Problems with script-driven dynamic player loading

I am attempting to load a dynamic player based on the browser being used, such as an ActiveX plugin for Internet Explorer using the object tag and VLC plugin for Firefox and Google Chrome using the embed tag. In order to achieve this, I have included a scr ...

How to divide an HTML string into an array using PHP

I am in need of some assistance from you all. The issue I am facing involves dealing with a string of HTML that looks like this: <h4>Some title here</h4> <p>Lorem ipsum dolor</p> (some other HTML here) <h4>Some other title ...

Ensure that Colorbox remains centrally positioned even while scrolling

I have noticed a difference in behavior between thickbox and colorbox when it comes to scrolling. Thickbox always stays centered on the screen even when the user scrolls vertically, while colorbox fades out and leaves just a grayed background. Is there a w ...

Is add1 missing from the DOM? Learn how to include it

Having an issue with Java-Script and an HTML form. The scenario is that there's a main form with an "Add" button, which when clicked should display a second form. Next to the second form is another button labeled "Add1," which ideally should trigger ...

Display a D3 Collapsible Tree visualization using information stored in a variable

I am currently working on an app that requires the display of a collapsible tree graph using D3. The data needed for this graph is not stored in a file, but rather within the database. It is retrieved through an Ajax call to a rest service and then passed ...

Utilize Python to extract a table from an HTML document

I would like to retrieve a table from an HTML file. Below is the code-snippet I have written in order to extract the first table: import urllib2 import os import time import traceback from bs4 import BeautifulSoup #find('table',{'class&ap ...

The success function in AJax does not properly execute on Safari browsers

Here is an example of my AJAX function: $.ajax({ url: "thankyou", type: "POST", data: arr, tryCount : 0, retryLimit : 3, success: function(response) { if(response == "Success"){ location.href = "/thankyou.html"; }else{console.l ...

"Null" is the value assigned to a JavaScript variable

I am encountering an issue on line 30 with the $.each(data.menu, function (). The console is indicating that "data is null". Can someone clarify what's happening? Thank you! function getFoodMenuData () { var url = 'http://localhost:88 ...

Having trouble retrieving PHP variable values using JavaScript?

<div id="div01">01</div> <div id="div02">02</div> <img src="../img/logo.png" onclick="blueSky()"/> js function blueSky() { $.ajax({ type:'GET', url: 'test.php', success: function(respond) { document.ge ...

Adding an image to Select2 dropdown using data fetched from MySQL and PHP using AJAX - Tips and tricks!

I need help figuring out how to add an image in front of the options in a searchable dropdown list that I created. The data for the list is coming from a MySQL database using PHP and AJAX. Currently, I am using the Select2 plugin and have successfully impl ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Do not exceed 3 elements in a row when using Bootstrap's col-auto class

col-auto is excellent. It effortlessly arranges items by size in a row, but I need it to strictly limit the number of items in each row to a maximum of 3. Each row should only contain between 1-3 items. <link rel="stylesheet" href="https://cdn.jsdeli ...