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

Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method. However, every time I try to do this, the value logged is always "0" instead of the actual le ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

Dealing with multiple jQuery ajax requests - strategies for managing them

Whenever I click the button quickly while there is jQuery Ajax loading, it seems to get stuck. How can I manage multiple requests being fired at the same time? What is the solution for the following: Cancel/abort all previous requests and only handle th ...

Interactive search tool for toggling visibility of elements

Hello everyone, this is my initial post on StackOverflow. Keeping my fingers crossed that it goes smoothly! <input type="Text" id="filterTextBox" placeholder="Filter by name"/> <script type="text/javascript" src="/resources/events.js"></scr ...

Conceal form upon submission with jQuery

Is it possible to have a html form inside a table and then hide it once the form is submitted? The Form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <tr> <td colspan="3"> <h ...

NodeJS Fork - React each instance a new line is detected from the child process

I am currently working on creating a NodeJS function (on Windows7) that listens to a subprocess and handles each newline sent through the subprocess in Node. The following example demonstrates this: var express = require('express'); var app = ex ...

Heroku-hosted application experiencing issues with loading website content

I have been working on a nodejs application that serves a web page using express and also functions as a discord bot. The app runs smoothly on localhost with both the web page and discord functionalities working correctly. However, when I deploy it to Hero ...

What is the reason behind HTML comment delimiters failing to function within HTML style tags?

Currently, I am utilizing CSS and HTML in my project. To implement styles, I am utilizing both an external stylesheet as well as a "style" element within the HTML to override certain styles. However, I have encountered an issue. When I insert an HTML comm ...

A guide on incorporating text into a file utilizing JSP within HTML

I am working on a project that includes a JSP file and a .txt file. The JSP file contains a text field and a button, where the user can enter a text and click the button to store it in the .txt file. I have provided my code below, but I seem to be missin ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Combining a JavaScript NPM project with Spring Boot Integration

Recently, I built a frontend application in React.js using NPM and utilized IntelliJ IDEA as my IDE for development. Additionally, I have set up a backend system using Spring Boot, which was also developed in IntelliJ IDEA separately. My current goal is t ...

How to handle blank property values in JavaScript objects and convert them to null in an ASP.NET Web API

Hey there! I'm facing an issue where when I post a JavaScript object to an ASP.NET Web API, some property values are blank like the example below: var o={ ID=1, Fname="Tom", Mname="", Lname="Wilson" } However, in the Web ...

Looking for a solution to troubleshoot issues with the updateServing function in JavaScript?

I am attempting to create a function that will calculate the portion sizes for the ingredients on my website. This function is located in the Recipe.js file and appears as follows: updateServings(type) { // Servings const newServings ...

Using the KnockOut js script tag does not result in proper application of data binding

Being new to knockout js, I found that the official documentation lacked a complete html file example. This led me to write my own script tags, which initially resulted in unexpected behavior of my html markups. Strangely enough, simply rearranging the pos ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

Issues with CSS styling are affecting the display of a form

Hey there! I was working on creating an order form for my website, and everything was going smoothly until I hit a snag while styling the webpage. The problem is that the legends of the form are extending all the way to the right side of the page, and the ...

Guide on implementing enums (or const) in VueJS

Seeking help on a seemingly simple task, I am trying to understand how to use "enums" in VueJS. In my file named LandingPage.js, I have the following code: const Form = { LOGIN: 0, SIGN_UP: 1, FORGOT_PASSWORD: 2, }; function main() { new Vue({ ...

Designing a unique CSS border for custom list item bullets

I'm currently exploring the possibility of implementing a CSS border around an image that I have imported as a custom bullet for my list items: ul { list-style: none; margin-right: 0; padding-left: 0; list-style-position: inside; } ul > ...

Select the radio button by hovering the mouse over it

Is there a way to check my radio buttons when hovering over them without having to click? I want to display photos based on the selected radio button. I attempted this using JQuery, but I am still learning and consider myself a beginner. ...

Generate an HTML dropdown menu based on the item selected from the autocomplete input field

I have a PHP page that searches the database and returns JSON results to an autocomplete input field: When I display the response from the PHP file (as shown above), it looks like this: { "success": true, "results": [{ "name": "Bananas, r ...