Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve this effect.

Code

HTML

<div class='box'></div>

CSS

.box {          
    width: 250px;
    height: 100px;    
    border: 1px #000 solid;
}

.red {
    background: red;
}

.blue {
    background: blue;
}

Javascript

$('div').click(function() {
    $(this).addClass('red');
});

link of jsfiddle

Answer №1

Experiment with toggleClass as shown below:

$('span').click(function() {
    $(this).toggleClass("highlight");
});    

To switch between two styles, such as bold and italic, you can do this:

$('span').click(function() {
    $(this).toggleClass("bold italic");
});

Answer №2

To transition from white to red, and then red to blue, the toggleClass() method cannot be used. It is necessary to implement some basic conditions to determine which class should be added:

$('div').click(function() {
    var $this = $(this);
    if ($this.hasClass('blue')) {
        $this.removeClass();
    } else if ($this.hasClass('red')) {
        $this.removeClass('red').addClass('blue');
    } else {
        $this.addClass('red');
    }
});

Check out this example on JSFiddle

If you simply need to toggle between the red and blue classes, include one of these classes in the HTML markup so they can be switched easily:

<div class="blue">Hello World!</div>

Then utilize the toggleClass() method:

$('div').click(function() {
    $(this).toggleClass('red blue');
});

View another example on JSFiddle

Answer №3

Utilize the hasClass() method.

.hasClass()

To verify the current class being used, implement code like this:

$('div').click(function() {
    if($('div').hasClass('red')) {       
        $(this).removeClass('red').addClass('blue');
    }
    else{
        $(this).removeClass('blue').addClass('red');
    }
});

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 is the best way to align flexbox to the left?

I'm having trouble aligning the FileCard component to the start of the container. I attempted using flex-start in my styling, but the FileCards are still centered. This is the current code snippet: <div v-if="posts" ...

Learn the process of utilizing signed URLs in conjunction with ReactJS to securely store files in AWS

I am currently working on a form where I need to attach images along with regular text inputs in order to submit data to my MongoDB. Here is the code for my post creation function: const [postData, setPostData] = useState({ text: '', i ...

When sending an Axios POST request, a "Network Error" message may be received even when the status code is 200 and there is a valid response

Currently, I am utilizing Vue JS version 2.5 along with Axios: "vue": "^2.5.17", "vue-axios": "^2.1.4", "axios": "^0.18.0", The main issue I am facing involves making a POST call like so: const data = querystring.stringify({ 'email& ...

Retrieve a specific element from a table using the value of another element as a

Is there a way to extract the phone number (located in the second <td>) from this code when the img src is set as picto_telephone.jpg? <tr> <td valign="top"><img src="picto_telephone.jpg" alt="" border="0"></td> <td va ...

Controller receiving null arrays from Ajax post

Every time I send null arrays through AJAX to a controller, even though the controller code looks like this: [HttpPost] public decimal CalculatePrice(PaintballItemQuantity[] piq_tab, EventOtherOption[] eoo_tab, int VAT = 8) { ... } Here's t ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Error message: 'The menu widget instance does not have a method called 'instance' in Wordpress.'

Currently utilizing WordPress version 4.7.3, I recently installed a new theme and encountered an issue in the console related to a textarea element. An uncaught error is being displayed: no such method 'instance' for menu widget instance The ...

Difficulty in packaging JavaScript resources within Laravel Project

Having trouble setting JS functions as global in my project: In the 'resources\js"', I have: numerosALetras.js: /////////////////////////// function unidades_nal(n){ ... } function decenas_nal(n){ ... } function centenas_nal(n){ ...

Obtain the ID of a YouTube video from an iFrame link using jQuery

Check out this YouTube video: iframe width="560" height="315" src="//www.youtube.com/embed/XbGs_qK2PQA" frameborder="0" allowfullscreen></iframe>` (Hell Yeah! Eminem :P) I only want to extract "XbGs_qK2PQA" from the link provided. Using $(&apo ...

Angular 8 utilizes JavaScript for its programming language

Looking for a solution in JavaScript - check out: codepen.io/skovtun/pen/VwLvXPB Struggling to find an equivalent for Angular 8+. I want the center block to maintain a fixed width of 1200px, and automatically compress when the left, right, or both sideb ...

Unusual shift in the modal's behavior occurs when the parent component's style.transform is applied

I have encountered an unusual issue with a modal's appearance and functionality. The modal is designed to enlarge images sent in a chat, with the chat upload preview div serving as the parent element and the modal as the child element. This strange be ...

Call a function in jQuery from outside

Encountering an issue when trying to call a function from a separate JavaScript file. In the HTML file named "a.html," here is the content: <html> <head> <script src="${resource(dir: 'js/demo', file: '.js')}"></ ...

Optimizing performance: Making the most of mongoose updateMany middleware

PROBLEM SOLVED: SOLUTION PROVIDED BELOW I have a piece of code where I am updating elements one by one: //registerCustomers.js const CustomerRegistrationCode = require("../models/CustomerRegistrationCode"); const setRegCodesToUsed = async (regC ...

Attempting to generate a nested array structure in order to produce a JSON object for output

I am currently working on a JavaScript script that interacts with the Netsuite ERP platform to retrieve data. Currently, the script is returning data in an array format, specifically product information. While this is functional, I would prefer it to retu ...

Use Javascript to toggle the display to none for a specific table row (tr)

Is there a way to implement JavaScript code that will hide a specific table row using display:none;, and then reveal it again when a button is clicked? ...

What is the best way to arrange cards in a specific order with breaks in between each flip

I am currently working on creating flip cards using HTML and CSS. I have successfully implemented the hover effect which flips the cards when hovered over. Now, my goal is to make the cards automatically flip one after the other at specific time intervals ...

How to make your divs stand out using Bootstrap

Can anyone assist me in aligning my divs based on the example below? Here is what I have achieved so far: I am struggling to apply spacing between the two divs, and they are not of equal height. My HTML: <div class="container - fluid"> ...

Does the Mirage addon work effectively in the ember.js tutorial?

Following the ember.js tutorial, I'm facing a roadblock at this particular stage: (especially when implementing the Mirage add-on). I've made changes to the mirage/config.js file as advised but still unable to display the Mirage data. Despite ...

numbered navigation jquery plugin

Can anyone recommend a jQuery plugin or alternative solution for creating a navigation system for comments similar to YouTube? Here is the link for reference: Thank you in advance. ...

d3.json is unable to parse a value of 'Infinity

My goal is to retrieve data from an SQLite database and convert it into JSON format for use with d3.js in order to create a graph. I have successfully obtained this data in JSON format using the following URL: http://localhost:8085/SQLQuery/?date1=2019-03 ...