Changing CSS classes with each click of the user, using Jquery

Looking for a way to seamlessly switch between two links with different CSS classes each time a user clicks? Here's what's currently happening:

<a class="class1" id="class1">Class1</a>
<a class="class2" id="class2">Class2</a>

As it stands, the code only works once. Subsequent clicks do not produce the desired result:

$("#class1").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

$("#class2").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

The objective is to alter the color through CSS.

Answer №1

Both methods are essentially performing the same function. The issue arises from assigning the same class to each tag, resulting in it only working correctly the first time. On subsequent attempts, it simply resets the current class. Wouldn't it be better to revise the code to something like this instead?

$("#class1").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

$("#class2").click(function(){
    $("#class1").removeClass().addClass("class1");
    $("#class2").removeClass().addClass("class2");
})

Answer №2

If you want to toggle multiple classes, you can use the toggleClass method.

$('.red,.blue').click(function() {
  $(this).toggleClass('red blue');
});
.red { background-color:red }
.blue { background-color:blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="red">One</div>
<div class="blue">Blue</div>

Answer №3

To target elements whose class name starts with "class", use the selector "[class^=class]". Extract characters from a string up to the last character by using .slice() with the parameters 0, -1. Check if the last character is 1 or 2 using the == comparison operator. Toggle the last character to the opposite value for matches: 1 becomes "2", and 2 becomes "1" in the class name of the element.

$("[class^=class]").click(function() {
  var className = this.className;
  this.className = className.slice(0, -1) + (className[className.length - 1] == 1 ? 2 : 1);      
});
.class1 {
  color: blue;
}

.class2 {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="class1" id="class1">Class1</a>
 <a class="class2" id="clas2">Class2</a>

Answer №4

I have successfully implemented the toggleClass function using JSFIDDLE. You can view the demo here.

This is the HTML code snippet:

<a class="class1" id="class1">Class1</a>
<a class="class1" id="class2">Class2</a>

Below is the JavaScript code used:

 $(document).ready(function(){
    $(".class1").click(function(e){
      e.preventDefault();
        $(this).toggleClass("class2")
    });
 });

And here is the CSS styling applied:

.class1{
  background-color:green; 
}
.class2{
  background-color:red;
}

Answer №5

When you select class1 once, it switches from having the class class1 to having the class class2.

However, if you click it again, because class1 is already set to class2, it remains unchanged.

A possible solution would be:

var class1check = 0;
$("#class1").click(function() {
    if (class1check === 0) {
        var addclass1 = "class2";
        var addclass2 = "class1";
    }
    else {
        var addclass1 = "class1";
        var addclass2 = "class2";
        class1check = 0;
    }
    $("#class1").removeClass().addClass(addclass1);
    $("#class2").removeClass().addClass(addclass2);
});

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

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

How do you feel about sharing HTML files online?

I have a project in .NET 2.0 where I am creating a control that allows users to input HTML into a textarea and then upload it. The issue is that .NET requires me to set ValidateRequest=false on the page for the upload to work, which can potentially creat ...

The Typeahead function encountered an error: it seems that the toLowerCase method is not

Good day. Can you please review my script below? Here is my JavaScript code: $(document).ready(function(){ $("#outlet").typeahead({ source: function(query, process) { $.ajax({ url: '<?=base_url() ...

The DOM lacks the assigned 'id' in the HTML

While working in the Moodle platform (version 3.5.7) using the Atto editor in both Chrome and Firefox, I have been attempting to assign an ID to a specific row class called "span9". My main goal is to give this element a unique ID and then reference it wit ...

Trouble with ajax call in Internet Explorer 8

Seeking assistance with a straightforward ajax request triggered by a user altering a select element. Implemented using jquery .ajax, the current functionality (which works in all browsers except Internet Explorer) involves loading a .html file via ajax, ...

instructions on invoking a function within the knockout $.getJSON() operation

I am currently experimenting with a basic knockout script (still in the learning process). $.getJSON(clientUrl + "/list/" + 1, function (data) { var viewModel = { clients: ko.observableArray(data) }; ko.applyBindings(viewModel); }); The initial arg ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

What is the reason behind the failure of the jquery.hide() function on this particular UL element?

Although the submenu displays correctly, it refuses to hide when using the mouseleave function. Oddly enough, a console.log() confirms that an event does trigger at the right moment when the mouse exits the <ul>, yet the submenu remains visible for ...

Incorporating fancybox on a dynamically loaded AJAX page

After searching extensively within this group and on Google, I have yet to find any answers to my problem. It seems that others have encountered the same issue, but existing threads did not provide a solution. So here I am seeking assistance. The question ...

What are the essential tools needed to extract, interact, and evaluate information from a webpage?

Just trying to figure out the most effective plan of action and required tools/frameworks for this task: 1. Access webpage 2. Navigate to specific page by clicking buttons and filling in text boxes for search 3-4 Repeat 3. Retrieve HTML from page and s ...

Utilize Google Charts Table Chart to extract data from an object-literal notation data source

Here's a look at the data source and Listener function: Data Source var data = new google.visualization.DataTable( { cols: [{ type: 'string', label: 'Col1' }, ...

Can fog be applied from a fixed location within a three.js scene without being tied to the camera's position?

Is it feasible to render fog in such a way that an avatar on a terrain remains clear while the surrounding area gradually fades into the mist, especially when the camera is positioned overhead at a distance? ...

"Encountering a 404 error while using Struts ajax

config.xml file <package name="admin" extends="struts-default" namespace="/admin"> <!-- Implement Login Functionality --> <interceptors> <interceptor class="AdminLoginController" name="loginStack"></interceptor> <intercep ...

Error: An unrecognized symbol '<' was encountered while utilizing $routeparams

In my Angular application with MongoDB, Express, and Node.js, I have a list of flats and I want to add an "Edit" option for each flat. Below is a snippet from my api.js file: api.route('/flats/:id') .get(function(req, res){ Flat.findById(r ...

What is the best way to begin the main page content below the stationary header in order to prevent any overlap with the hyperlink section?

I have created this HTML page, but I am facing an issue where the hyperlinked sections overlap with the static header when clicked on. I want all linked sections to appear below the header and each section to have different dimensions within the iframe. I ...

The picture won't stay within the confines of the container

As I work on my fitness site, I wanted to incorporate a sponsor section. While exploring some code that matched the style of my website, I discovered this snippet below. However, being new to CSS, I struggled with fixing it to ensure that the images fit ...

Tips for resolving CORS error in swagger-ui-express

I'm encountering a "Possible cross-origin (CORS) issue?" error with Spec2 while running this swagger-ui-express application: const express = require('express'); var cors = require('cors'); const app = express(); const swaggerUi = ...

How come the values in my object remain inaccessible even after assigning values to it with navigator.geolocation.getCurrentPosition() and returning it?

After successfully assigning values to my pos object within the whereAmI function using navigator.geolocation.getCurrentPosition(), I can confirm that lat and lng are present inside the object. However, attempting to access these properties later on resu ...

Tips for creating the ultimate footer section on your webpage

I'm trying to position the footer div (id="Footer") 10px from the bottom of the screen. Regardless of whether the page content fills the entire height of the screen or creates a scroll area, I want the div to always be at the very bottom with a 10px m ...

The quickest regular expression match possible if it is already a subsection of another match

Is there a simple way to find the shortest match in a long text where strings are repeated? I'm having trouble because matches within already matched text aren't being found. Here's an example of the issue: Using code: "ababc".match(/a.+c ...