How to Conditionally Change CSS Styles with Js

How can I conditionally change css styles with js?

If you want to change a single style of an element using JavaScript, use

document.getElementById(id).style.property = new style

eg :

document.getElementById("myDiv").style.color= "red";

To add a new CSS class to an element, use

document.getElementById(id).classList.add("mystyle");

To remove

document.getElementById(id).classList.remove("mystyle");

Demo :

function changeSingleStyle() {  var color = document.getElementById("myDiv").style.color;  if (color === "red")    document.getElementById("myDiv").style.color = "yellow";  else    document.getElementById("myDiv").style.color = "red";}function addClass() {    document.getElementById("myDiv").classList.add("mystyle");}function removeClass() {    document.getElementById("myDiv").classList.remove("mystyle");}
.mystyle {  color : red;  background: green;  font-size: 50px;}
<div id="myDiv"> This is a div </div><button onclick="changeSingleStyle()">changeSingleStyle</button><button onclick="addClass()">addClass</button><button onclick="removeClass()">removeClass</button>

Correct way to handle conditional styling in React

If you prefer to use a class name, by all means use a class name.

className={completed ? 'text-strike' : null}

You may also find the classnames package helpful. With it, your code would look like this:

className={classNames({ 'text-strike': completed })}

There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.

POSTSCRIPT [06-AUG-2019]

Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.

CSS changes its property based on Javascript condition

That should be fairly easy, essentially you just need to change the property using the CSS method(http://api.jquery.com/css/) on document.ready...

So the jQuery solution would be:

$(document).ready(function(){
if (browser == "IE8"){
$('.divFooter').css('position','absolute');
} else {
$('.divFooter').css('position','relative');
}
});

You could also do this with vanilla JS using the Style Object(http://www.w3schools.com/jsref/dom_obj_style.asp) like this:

//set variable for your div (should likely be ID instead of class but no matter)
var yourDiv = document.getElementsByClassName("divFooter");

//if statement to set position
if (browser == "IE8"){
yourDiv.style.position = "absolute";
} else {
yourDiv.style.position = "relative";
}

How to Conditionally Add styles in react?

I have created a simple app to show you how it can be achieved, I hope this will give you a general idea. You can't use it as is cause I guess the shape of your question answer object may be different than the one I used.

Working App: StackBlitz

Sample Image

import React, { useState, useEffect } from "react";
import "./style.css";
import { questions } from "./questions";
export default function App() {
const [selectedAns, setSelectedAns] = useState("");
const [index, setIndex] = useState(0);
const [score, setScore] = useState(0);
const [shadow, setShadow] = useState(null);

useEffect(() => {
console.log(selectedAns);
}, [selectedAns]);
return (
<div>
<h3>{questions[index]?.question}</h3>
<div
className="ans"
onClick={() => {
setSelectedAns(questions[index]?.correct_answer);
}}
style={{
boxShadow:
selectedAns == questions[index]?.correct_answer
? selectedAns == questions[index]?.correct_answer
? "0 0 5px 2px rgba(1, 156, 48 , 0.3)"
: "0 0 5px 2px rgba(255, 0, 0, 0.3)"
: null
}}
>
{questions[index]?.correct_answer}
</div>
{questions[index]?.incorrect_answers?.map(answer => (
<div
className="ans"
onClick={() => {
setSelectedAns(answer);
console.log(answer);
}}
style={{
boxShadow:
selectedAns !== answer
? null
: selectedAns == questions[index]?.correct_answer
? "0 0 5px 2px rgba(1, 156, 48 , 0.3)"
: "0 0 5px 2px rgba(255, 0, 0, 0.3)"
}}
>
{answer}
</div>
))}
<button
className="ans"
onClick={() => {
setIndex(index + 1);
if (questions[index]?.correct_answer == selectedAns) {
setScore(score + 1);
}
setSelectedAns("");
}}
>
NEXT
</button>
<h3>YOUR SCORE: {score}</h3>
</div>
);
}

How do I conditionally apply CSS styles in AngularJS?

Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:

  • ng-class - use when the set of CSS styles is static/known ahead of time
  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)
  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)
  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)
  • ng-disabled and ng-readonly - use to restrict form element behavior
  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations

The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.

When the user changes the UI, Angular will automatically update the associated elements on the page.


Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

ng-class accepts an "expression" that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values

Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:

<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
... HTML to display the item ...
<input type="checkbox" ng-model="item.checked">
</div>

Above, we used ng-class expression type #3 - a map/object of class names to boolean values.


Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

ng-style accepts an "expression" that must evaluate to:

  1. an map/object of CSS style names to CSS values

For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):

<div class="main-body" ng-style="{color: myColor}">
...
<input type="text" ng-model="myColor" placeholder="enter a color name">


Fiddle for both of the above.

The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.



Related Topics



Leave a reply



Submit