Ways to incorporate or eliminate a class on a hyperlink

I am currently working with bootstrap tabs, and I have four of them. My goal is to assign a different color to each tab, which should change when the user clicks on them. Bootstrap's "active" class doesn't seem to be effective in this case because I want each tab to have a unique color. As a solution, I decided to use a jQuery function to add a class when a tab is clicked, but I am unsure of how to remove the class when another tab is clicked.

Is there a way to pass two values to a function – one from one link and another from a different link? For example, when I click on "cars," I want to remove the class from "trucks," and vice versa.

HTML

<ul class="nav nav-tabs" role="tablist">
            <li class="active"><a href="#home" role="tab" data-toggle="tab">Link 1</a></li>
            <li><a href="#link2" role="tab" data-toggle="tab">Link 2</a></li>
            <li><a href="#link3" role="tab" data-toggle="tab" id="cars">Link 2</a></li>
            <li><a href="#link4" role="tab" data-toggle="tab" id="trucks" >Link 3</a></li>
          </ul>

CSS

#cars
{
    color: #FFF; 
    background: #ec7501;
    background: -moz-linear-gradient(top, #ec7501 1%, #c46200 56%, #ec7501 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,#ec7501), color-stop(56%,#c46200), color-stop(100%,#ec7501));
    background: -webkit-linear-gradient(top, #ec7501 1%,#c46200 56%,#ec7501 100%);
    background: -o-linear-gradient(top, #ec7501 1%,#c46200 56%,#ec7501 100%);
    background: -ms-linear-gradient(top, #ec7501 1%,#c46200 56%,#ec7501 100%);
    background: linear-gradient(to bottom, #ec7501 1%,#c46200 56%,#ec7501 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ec7501', endColorstr='#ec7501',GradientType=0 );
    border-top: 2px solid #de9d5b;
    border-bottom: 2px solid #a64800;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
}

.activeTab
{
    color:#000 !important;
    background:#FFF !important;
}

JS edits based on Ed Cottrell comments,

('#cars, #trucks').on('click', function() {
    changeColor($(this)); // passes the element itself
});

function changeColor($elem)
{
    $('.activeTab').removeClass('activeTab'); // remove the class from elements that have it
    $elem.addClass('activeTab');
}

Answer №1

For removing a class in jQuery, you can use the $(selector).removeClass(class). Avoid using inline onclick triggers with jQuery and opt for dynamic bindings.

Here's an example:

$('#bikes').on('click', function() {
    changeColor('bikes');
});

$('#another_tab').on('click', function() {
    $('.activeTab').removeClass('activeTab'); // to remove the class from elements having it
    doSomethingDifferent();
});

Update: If you prefer something different based on your feedback:

$('#bikes, #vans').on('click', function() {
    changeColor($(this).prop('id')); // passing the clicked element's id
});

function changeColor(id)
{
    $('.activeTab').removeClass('activeTab'); // to clear the class from relevant elements
    $('#' + id).addClass('activeTab');
}

If you want an even simpler approach without involving ids:

$('#bikes, #vans').on('click', function() {
    changeColor($(this)); // directly passing the clicked element
});

function changeColor($element)
{
    $('.activeTab').removeClass('activeTab'); // ensuring the class is removed from suitable elements
    $element.addClass('activeTab');
}

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

Store a designated text into a MySQL database by extracting it from every file within a directory

I've encountered various methods for "crawling" websites, but none seem to fit my requirements. I am interested in being able to extract data from each file within an online directory and then store the extracted information into a MySQL database: h ...

jQuery cycle hovers above all other elements on the page

Hello, I'm currently experiencing an issue with replacing my Flash video with a jQuery cycle on massageeducator.com's home page. Even though the cycle is functioning properly, the images are not staying within the editable region as intended - in ...

The necessary parameters are not provided for [Route: bill] [URI: bill/{id}]

I'm having trouble locating the error in my code. Here is my controller: public function editBill(Request $req) { $customerInfo=Customer::where('id',$req->id)->first(); $billInfo=Bill::where('id',$req->id)->get( ...

Not able to properly display side-by-side with bootstrap due to an angular component present

<form> <div class="row form-check"> <label class="form-check-label" for="communes">Choose a town :</label> <app-communes id="communes" anneeCOG="2023"></app- ...

Sending multiple error messages from PHP to jQuery as an array, encoded in JSON format

Having some difficulty outputting multiple errors as arrays from my PHP file in JSON format to jQuery. Typically, PHP data can be encoded as JSON and then sent to jQuery for displaying the code as either an Ajax success or error response. Everything works ...

Converting Interfaces from Typescript to Javascript

Can the interface in typescript be converted into Javascript? If so, what is the process for converting the typescript code shown below into Javascript. interface xyz{ something? : string, somethingStyle? : Textstyle } ...

Ensuring Equal Padding on Both Sides of a Div by Setting its Width

In search of a div that houses multiple inner divs with equal padding on the left and right edges. This is crucial for maintaining a fluid layout where the distance between the inner divs and outer div border remains consistent even when the window size ch ...

AJAX request in jQuery version 1.4.4 and above will convert an empty array or object into a string

My JavaScript object is causing issues when trying to AJAX POST to a PHP script. While it used to work fine in jQuery 1.4.1, versions 1.4.4 and above now convert empty arrays or objects into strings like "0", which is not the desired behavior. JS: $(docu ...

Using PHP to enhance Bootstrap grid functionality

Trying to create a custom theme for my Omeka site using PHP to pull in item components. Each item is enclosed in its own div, and I'm attempting to arrange them in a grid using Bootstrap. However, they are currently stacking vertically instead of hori ...

Detect if the content loaded in the web view is a PDF file and provide a downloadable option

I am using wkWebView to access research papers from IEEE, Science Direct, and other sources. When I click on a PDF in the research papers, it gets loaded into the webview. Is there a way to detect and enable a download icon in wkWebView? Attempted Solutio ...

Issue with Three JS where the BoundingBox does not update correctly following rotation operations

I am trying to determine the bounding box of a geometry after applying rotations to it. I obtained the rotation code from the sample editor in Three JS: object.rotation.x = xRadians; object.rotation.y = yRdians; object.rotation.z = zRadians This rotatio ...

Formatting dates in AngularJS

Is there a way to customize the date format within an ng-repeat loop? I attempted to format it as shown below <div class="col-date">{{row.Calendar.start | date : "dd.MM.y"}}</div> However, it did not produce the desired outcome. What is th ...

Load data from a file into a dropdown menu using node.js

Exploring the realm of front end development on my own has been quite a challenge. I am currently struggling with the concept of populating a drop down box with data from a file. While utilizing node and JavaScript, I have decided to stick to these techn ...

How to extract data from URLs in Angular

Looking into how to extract a specific value from the URL within Angular for parsing purposes. For example: http://localhost:1337/doc-home/#/tips/5?paginatePage=1 The goal is to retrieve the value "5". HTML snippet: <a href="#/tips/comments/{{ tip ...

Axios failing to transmit cookie information, despite setting withCredentials to true

Exploring the capabilities of React and Express to handle requests while including cookies. The communication between client-side and server-side is successful, however, the cookies are not being transmitted. On the client-side: import axios from 'axi ...

Hide the mobile menu after an option is clicked

I managed to implement a mobile menu on my single-page website by utilizing code I found online. Currently, the menu only opens or closes when the main navigation bar is selected due to the JavaScript I have integrated. Is it feasible for the menu to autom ...

Is there a more effective method for detecting changes in a class variable in JavaScript, aside from using setInterval()?

Is there a more readable way to monitor changes of a class variable from its instance? Although I can use setInterval() to achieve this, the code becomes quite difficult to read. let calibrator = new Calibrator("hardwareName"); calibrator.connect(); let ...

Tips for confirming a date format within an Angular application

Recently, I've been diving into the world of Angular Validations to ensure pattern matching and field requirements are met in my projects. Despite finding numerous resources online on how to implement this feature, I've encountered some challenge ...

Encountering a problematic JQuery Ajax request to a RESTful API

I am currently in the process of trying to authenticate against demo webservices that were developed by one of my colleagues. While Cross-origin resource sharing is allowed and functions perfectly when I attempt to call from the Advanced Rest Client plugin ...

Once more delving into Angular.js $scope and controllers

After spending several hours trying to troubleshoot the issue with my angular $scope, I still can't seem to pinpoint what's wrong. I'm using Angular.js with Ionic in my app, and I believe the problem lies within Angular. Within my app, I ha ...