Maintaining CSS3 Color Styling Even After Class Removal Using Javascript

I am facing a challenge with dynamically changing color styling of an element using Javascript. The colors are set by the ids #clock and #quantity. When a certain condition is met, I add a class to change the color styling, and remove it when the condition changes back. However, the issue is that after removing the class, the color style persists instead of reverting to the colors styled by the previous 2 id's.

One way to solve this would be to remove the ids and reapply them dynamically with Javascript. But I'm exploring if there might be a more efficient solution?

<div id="clock">
    <div id="top-gradient"></div>
    <div id="time">
        <span id="zen9" class="quantity"></span> 
    </div>
    <div class="zentext">Server Monitor</div> 
</div>

Javascript:

bar = document.getElementById(id);
etop = bar.parentNode.parentElement;
ebottom = bar.parentNode.previousElementSibling;
etext = bar.parentNode.parentNode.childNodes[5];
if ( value >= threshold[id] && !(bar.classList.contains("zenRed"))) {
    bar.classList.add("redZen");
    etop.classList.add("redZenTop");
    ebottom.classList.add("redZenBottom");
    etext.classList.add("redZenText");
} else if ( value < threshold[id] && (bar.classList.contains("zenRed"))) {
    bar.classList.remove("redZen");
    etop.classList.remove("redZenTop");
    ebottom.classList.remove("redZenBottom");
    etext.classList.remove("redZenText");
}

Answer №1

Your request lacks sufficient information, but it seems you want to apply a class based on a condition and then remove it later.

Just a heads up, the element with the identifier #quantity is actually a class, not an id.

One way to achieve this is by using the toggle function from classList, which allows you to add or remove a class depending on its current state.

Does the following code snippet meet your requirements?

var bar =  document.getElementById('clock');
var foo =  document.getElementById('time');

bar.classList.toggle('redZen');
foo.classList.toggle('pinkZen');

Check out the jsFiddle example here

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

Transfer password securely through an ajax call

Is it secure to send a password through an Ajax request? I have a login box that makes an Ajax request to check the login credentials and receive a JSON Object with any errors. Would it be better to use form redirection instead? [EDIT] Storing the encry ...

Discovering the minimum and maximum Node.js versions that my Node.js application can support according to its dependencies

If I have 10 developer dependencies and 10 production dependencies, how can I decide on the minimum and maximum node versions required for a user to download or clone my node application and run it smoothly? How can I automate this process by analyzing all ...

The error message "TypeError: $(...).val(...).html is not a function" indicates that

When I receive a JSON array from an Ajax response, I attempt to populate a drop-down with it but encounter an error. The JSON array, after being stringified, looks like this: [{"ID":"1","NAME":"Nevpro"},{"ID":"9","NAME":"Tushar"}] <html> <s ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Converting Image to Base64 String and Parsing into a JSON Object

Hey there, I'm currently working on creating a form where users can input their information along with an image. My goal is to send all this data together in a JSON object back to the Node.js server. In order to include the image, I've been attem ...

Creating a nested list in AngularJS using the ng-repeat directive

My experience with AngularJS is limited, but I am tasked with modifying a web app that requires nesting lists inside each other: <ul class="first-level"> <li ng-repeat="item in list">{{item.parentNo1}} <ul class="level-2"> ...

Using local or session storages in Next.js: A beginner's guide

When I receive a response from my server-side rendered app, I am attempting to set an item in session storage. However, I am encountering an error stating that session storage is not defined. This is likely because on the server side, there are no storages ...

Unable to pass multiple objects as props in Vue component causing issues

Seeking help on passing multiple props to a component using v-for: <my-component v-for="(item, index) in items"></my-component> The data structure 'items' consists of: items: { 1: { name: "Apple", color: "Red" }, 2: { name: "Ba ...

Having trouble styling the image within a <section> tag using CSS

I've been attempting to incorporate an image into the PUG template engine of node.js using CSS, however, the image isn't showing up on the screen even though other properties are functioning correctly. Here is the code from the .PUG file section ...

Empty space found at the bottom of the webpage

Looking for help to remove the extra white space at the bottom of my upcoming portfolio website: The issue I'm facing is that the footer appears either too long or too short on most monitors. On tiny windows, there's a scroll and on larger resol ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

What are the steps for modifying the JSON data format in AngularJS?

As a newcomer to Angular JS, I am working with the following JSON data: { "CheckList": [ { "UnitClass": "Budget Space", "CheckListCategoryId": 1, "CheckListCategory": "DOORS", "CheckListItemId": 2, "CheckListItem": "Deadbolt, Lockse ...

React-native: Project encountered errors after the Catalina update

After upgrading my Mac OS from High Sierra to Catalina, I encountered an issue when trying to run my project. I followed the steps of running the command react-native init, pod install in the ios directory, and then attempted to run the iOS code using Xco ...

Having trouble with catching errors in try/catch using Async/Await in JavaScript?

I've encountered an issue with the JavaScript code snippet below while using async/await in our ES6 project. I've observed that a 404 response code is not triggering the catch block as expected. Moreover, the .json() method is causing a console e ...

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

tool that flips the text value in a textbox using jQuery

In my attempt to reverse the text written inside a textbox upon button click, I have made some progress. Here is what I have done so far in my HTML: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Untitled Document</titl ...

Updating a session or global variable cannot be read by an AJAX request

Currently using Flask with google-python-api-client for fetching data from Youtube. Experimenting with loading the next video asynchronously from the playlist upon button click. To achieve this, setting the nextPageToken parameter in the request is essent ...

Pass a variable value as a parameter to a jQuery function using code-behind

Within my code behind, I am retrieving the [IDphoto] from an SQL database. My goal now is to pass this IDphoto as a parameter to a jQuery function upon onClick. How can I achieve this? Code behind sb.AppendFormat("<a onclick='popup()' href=& ...

Guide on creating a hover-based side menu

I am looking to enhance the sub-menus like PRODUCT 1, PRODUCT 2, etc. by adding side menus that appear when hovering over them. Can anyone assist with implementing this feature in the code below? Below is the current code snippet: CSS: @import url(http: ...

function to grab the nearest html value from the td before

Link to JSFiddle <table> <tr> <td class="iwant">ttt</td> <td>some text <span class="txt">haha</span></td> </tr> </table> $(".txt").on("click", function() { alert($(th ...