"Creating a function that reverts a CSS class to its previous state when clicked using CSS and jQuery

I've got a <div> that starts with a blue background color and has a jQuery onclick event that changes the color to red. I'm trying to figure out how to make the div's background color change back to blue when the button is clicked again, and then return to red if clicked once more. Any suggestions on how to accomplish this?

Answer №1

Essential requirement.

$(".yourElement").click(function () {
   $(this).toggleClass("red");
});

The specified CSS properties

.yourDiv{ background-color: #1E90FF; }
.yourDiv.red { background-color:#FF0000; }

Answer №2

It's a bit unclear what you mean by clicking twice, so I have provided two potential solutions for you to consider.

The first box will change its background color to blue when clicked once, and back to black when clicked a second time (double-clicked).

The second box changes its background color with each click; alternating between green and yellow.

var box = document.getElementById('box'),
    box2 = document.getElementById('box2'),
    bool = true;
    
    box.addEventListener('click', function(){
      this.style.background = 'blue';
    });

    box.addEventListener('dblclick', function(){
      this.style.background = 'black';
    });

    box2.addEventListener('click', function(){
        if (bool) {
            this.style.background = 'yellow';
            bool = false;
        } else {
            this.style.background = 'green';
            bool = true;
        }
    });
#box {
  height: 100px;
  width: 100px;
  background: black;
  margin: 5px;
}
#box2 {
  height: 100px;
  width: 100px;
  background: green;
  margin: 5px;
}
<div id='box'></div>
<div id='box2'></div>

Answer №3

To effectively address your issue, it would be beneficial to provide a snippet of code that demonstrates how your problem can be resolved. Typically, the jquery onclick event can determine the color of a div by utilizing code resembling the following:

var currentColor = $('a').css("backgroundColor");

Subsequently, you can adjust the colors based on the existing color.

Answer №4

To clear the previous value using jQuery, simply pass an empty string to .css method like this: .css('background-color', '');

Answer №5

If you're working with Jquery, toggleClass is a great method to use for this purpose. Don't forget to check out the toggle method too.

 <style>
 .blue{
      background-color: blue;
 }
 .red{
      background-color: red;
 }
 </style>

 <div class="blue">
      ....
 </div>

 <script>

 $( ".blue, .red" ).click(function() {
   $( this ).toggleClass("blue");
   $( this ).toggleClass("red");
 });
</script>

p.s. I'm composing this on my phone

Answer №6

No need for jQuery, just apply CSS styling to a class and use Vanilla JavaScript to add or remove that class.

let body = document.querySelector('body'),
    box = document.querySelectorAll('.box');

body.addEventListener('click', function(e) {
  let cl = e.target.classList;
  if (cl.contains('box'))
    cl.toggle('active');
});
.box {
  background: blue;
  display:    inline-block;
  margin:     5px;
  height:     2.5rem;
  width:      2.5rem;
}

.active {
  background: red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

  • Adds a click event listener to the parent element (in this case, the body) instead of creating multiple listeners for each box element, improving performance
  • By checking the event target's class during the click event, we can determine whether it was a box that was clicked. This prevents adding the active class to unintended elements

To make the code even shorter, you can replace the if block with

cl.contains('box') && cl.toggle('active');
, which toggles the active class if the element has a box class.

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

Implement the backstretch plugin method within a jQuery $.ajax call

I am currently working on integrating an Instagram gallery into a responsive Wordpress theme and have encountered some challenges for which I would appreciate assistance. The process involves fetching the Instagram feed using ajax and jsonp, then appendin ...

Unable to modify the background image in CSS when hovering over

I am struggling with changing the background image of the included div when hovering over the col-lg-3 div. I have 6 col-lg-3 in my container, each containing another div with background images and various CSS properties. Despite trying to change the backg ...

How can ember-data search for a record using both an ID and extra criteria?

While exploring the Ember documentation, I learned that the find() method supports finding by id: this.store.find('post', 1); // => GET /posts/1 It also allows for searching with arbitrary parameters: this.store.find('post', { nam ...

Addressing the status bar gap issue on the iPhone X with Cordova for iOS 11.0

After receiving helpful feedback on my previous Cordova question regarding status bars, I've encountered a new issue with the iPhone X on iOS 11.0. I came across this thread: Users are reporting a white bar appearing specifically on the iPhone X run ...

Unable to apply a border to the button

I'm having trouble adding a border to my button on the website. I've tried setting the color, which works fine for the font color within the button, but the border properties are not working. Despite trying some highly rated solutions, none of th ...

Enhancing a custom component with a transition-group component

I have a unique component that needs to include a list using v-for beneath it. <rearrangeable> <div v-for="item in items">...</div> </rearrangeable> I'm attempting to incorporate a <transition-group> element for addi ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

Utilizing jQuery for interacting with iframes

My script functions perfectly on the page, but when I embed it using an iframe, the jQuery features stop working even though the script is written as usual. Even using $.noConflict(); does not resolve the issue. ...

The dataset remains undefined within the context of Vue.js

I am attempting to utilize the dataset property in Vue to retrieve the data-attribute of an element. Here is how I am implementing it: <ul id="filter"> <li><a class="filter-item" v-on:click="filterItems" data-letter="a" href="#"> ...

Using three.js to retrieve the camera's position using orbit controls

In my journey using three.js orbit controls, I have encountered a challenge of making a skybox follow the camera's position. Despite scouring the internet, I have not come across a suitable solution. My query is straightforward - how can I obtain the ...

Revolutionary web element

My vendor provides a convenient widget creation service that allows me to access their platform, input initial search form values, save them, and then easily embed the generated script code on my website to display a product search result widget. I am int ...

During the update from Three.js 68 to 69, an error occurred: Unable to access the property 'boundingSphere' of an undefined object

While upgrading my project from Three.js version 68 to version 69, I encountered an error stating Uncaught TypeError: Cannot read property 'boundingSphere' of undefined on line 6077 of Three.js v69: This error pertains to a function within the T ...

The behavior of CSS position: sticky varies depending on whether the user is scrolling up or scrolling down

I am experiencing an issue in my Vue CLI app where a component with the position: sticky CSS property is being partially hidden under the top of the browser when scrolling down, but works correctly when scrolling up. This behavior is also observed on my Ga ...

ajax - Text not appearing in Google's cached version

My website retrieves content using MS AJAX from an ASP.NET webservice. However, when I check the cached version on Google, I notice that the initial text is not displayed. I am wondering what would be the most effective method to ensure the website's ...

Utilizing the Intuit API in NodeJs to seamlessly attach images to items (products) in Quickbooks

I am currently working with the Quickbooks API and the NodeJS SDK (oauth-jsclient) and facing some challenges in uploading an image to an Inventory Item. According to the documentation (docs), it requires making a multipart/form-data post request to the en ...

Unselected default option in Angular 4's select dropdown

My goal is to use Angular to retrieve a value from a variable and display it as the first option in a select element, while keeping the rest of the options below static. The issue I am facing is that even though Angular is fetching the data successfully, t ...

Achieve centered alignment for a website with floated elements while displaying the complete container background color

I am currently working on a website that consists of the basic elements like Container, Header, Content, and Footer. The container has a background-color that should cover the entire content of the site, including the header, content, and footer. However, ...

Locate a specific item within an array using TypeScript

Looking for a more efficient solution to retrieve data from a collection in Typescript. The data is structured as follows: myData: { Id: string, Name: string, Address: string Salary: number phone: number } We have approximately 500 records, eac ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...