A guide to dynamically adjusting CSS with JavaScript

Currently, I am working on a complex animation project where I am experimenting with incorporating effects by dynamically adding classes based on the value that I receive.

I have various CSS classes at my disposal and I am seeking to understand how to effectively add them in this manner.

.. Class="box bottom right" 

For instance, when I introduce a new class (such as "red"), it should reflect in my code like so:

.. Class="box bottom right red" 

My objective is to modify the CSS according to the calculated value.

var els=2;

  function changeColor(els) {
    if (els > 0) {
            $("box bottom right").addClass("red");
    } else{
            $("box bottom right").addClass("green");
    };

  } 

Take a look at the code here: http://jsfiddle.net/BB6ED/1/

Answer №1

To target elements by class, you must use . in your code. Also, make sure to call your function on page load like this:

var count = 2;

function changeColor(count) {
    if (count > 0) {
            $(".box.bottom.right").addClass("red");
    } else {
            $(".box.bottom.right").addClass("green");
    }
}

changeColor(count);

Check out the updated Fiddle 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

The transition effect is not functioning properly in CSS and React.js

.cartBtn { appearance: none; outline: none; border: none; cursor: pointer; text-align: center; background-color: transparent; color: inherit; } .cartBtn:hover { color: black; } .cart { display: none; opacity: 0; transition: all 4s ea ...

Is it possible to shift the div inline-block using the CSS :after selector?

I'm looking to adjust the placement of the disk icon so that it aligns more with the baseline of the text without increasing the vertical space between lines. Below is the CSS code I've worked on so far: .openPage:after { content: ' &a ...

Ensure that the form redirects to website.com/test/ rather than website.com?name=

I am currently facing an issue while trying to create a search function for usernames. When I click the submit button, it redirects me to websitelink.com?=name=Nighel instead of going to websitelink.com/Nighel/ Even though I am using htaccess, the ?= form ...

I lost my header div when I made the transition from HTML 5 to XHTML 1 Transitional

Recently, I faced a challenge while transitioning a client's website pages to XHTML 1 Transitional in order to support an API from a company called Chamber Master. This particular API handles membership information, job postings, promotions, and other ...

Guide on repeatedly clicking the Cookie to enjoy Cookie Clicker on https://orteil.dashnet.org/cookieclicker/ with the help of Selenium and Python

I've been attempting to create a selenium program for playing Cookie Clicker, but I'm encountering some issues. Here's the code I have so far: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains P ...

Is it feasible to automatically fill out a separate form by clicking a link?

Seeking help with creating an Android app that can automatically populate the "RFC Emisor" and "RFC Receptor" fields on a specific web page: https://verificacfdi.facturaelectronica.sat.gob.mx. I believe the IDs for these inputs are: ctl00_MainContent_ ...

Activate Bootstrap tab show event upon clicking the next button

Seeking assistance with my jQuery code: $('#nexttab').click(function () { var tabToShow = $(this).attr("data-target"); if ($(tabToShow).length) { $('a[href="' + tabToShow + '&q ...

Validating textfields and dropdowns for dynamic HTML identifiers using jQuery

I am attempting to validate a dropdown and text field together. Both fields can either be left empty or both must be filled. The HTML ids are generated dynamically. I have tried the code below but it is not working as expected. Here are the resources I use ...

Incorporate a fresh value into an array within MongoDB

I'm attempting to add a new value to an array inside an object using the following method: await database.models.updateMany( { <queue> }, { $push: { object: { array: 'Hello, World!' }}}); However, instead of adding a new value, it del ...

Bringing a TypeScript module to life with a sprinkle of 'import

I am attempting to integrate the numbro JavaScript library into my TypeScript project. The numbro.d.ts file exports like this: declare const numbro: NumbroStatic; export default numbro; My simple import statement looks like this: import numbro from &apo ...

Tips for organizing and showcasing data in AngularJS

Recently, I developed a scope function that looks like this: $scope.sample = [ {'SUPNAME':'AAA','SUPCODE':'22671','SLIPNO':'18384','DESG':'1','iv':'1'}, ...

Maintain an active session during page reload

I recently inherited a codebase and noticed that the previous developer did not utilize cookies or local storage to store the token. I am contemplating sending the token to the client and storing it in local storage, but I'm unsure of how to persist t ...

Does CausesValidation validate all validators, including validation groups?

I have encountered an issue with my web page where I have 3 separate validation groups, but when I attempt to submit the form, I want all of the groups to validate simultaneously. It appears that using causesValidation="true" on the button does not trigge ...

Add HTML syntax highlighting to a text area for coding purposes

I am facing a seemingly straightforward issue, but I worry that it may be too complex for me to handle on my own. My goal is to incorporate a textarea into a webpage where users can input HTML code, click a button, and have the interpreted HTML displayed i ...

Using jQuery to save PHP form output into an Excel spreadsheet

I have a PHP-enabled form on my website for collecting Address details. Currently, the output is sent to my email inbox. However, I would like the output data to be saved in an external Excel file named "address.xls" using jQuery/JSON. The input fields of ...

Creating Custom Filters in Angular using Functions

Attempting to filter ng-repeat using a function instead of an actual filter has presented some challenges. The code snippet below demonstrates the attempt: <tr ng-repeat="(key, value) in dataObj| filter:dataFilter"> The intention is to define dataF ...

Rearrange the order of all elements following a specific li element to the beginning with the help of

How can we rearrange elements in a ul list using jQuery after selecting a specific li element? For example, moving all elements after the third li to the beginning. <ul> <li>1</li> <li>2</li> <li>3</li> <li>4 ...

Struggling to comprehend the node.js walker concept

I am struggling to grasp the concept of how the signature/header of the node.js walker functions. I understand that a walker can go through a directory and apply filters, but I'm unsure about how the signature of the .on function works. For example: ...

The :root selector has encountered a malfunction within the Angular component

I'm interested in experimenting with CSS variables in my Angular 11 component. <div class="main-content"> <a>Test Link</a> </div> Here is my app.component.css: div.main-content{ --main-color: red } a{ color: v ...

Encountering a 400 bad request error while trying to post data using

const fetch = require("node-fetch").default; let iApi = express.Router(); iApi.post("/update/:name/:value", async (req, res) => { const name = req.params["name"]; ...