Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to switch between two colours with javascript?

Tags:

javascript

css

Javascript beginner here. I essentially want to make a simple switch. If an element is black, change it to white. If it is white, change it to black.

function changeClass() {
    if (document.getElementById('myButton').style.backgroundColor == "white") {
        document.getElementById('myButton').style.backgroundColor = "black";
    } else {
        document.getElementById('myButton').style.backgroundColor = "white";
    }
}
<button class="normal" id="myButton" onclick='changeClass()' >Change Colour</button>

This code is quite messy though. Is there a better way to do this?

like image 363
Simon Kiely Avatar asked May 13 '19 10:05

Simon Kiely


People also ask

Can you change color in JavaScript?

Answer: Use the JavaScript style property You can easily change the background color of a webpage i.e. the <body> element or any other element dynamically by using its style property in JavaScript.

How do you give a color in JavaScript?

Use the String fontcolor() Method We can apply the fontcolor() method on any text string, and it returns the <font> HTML element with the color attribute.

Which property is used to change the background color in JavaScript?

The background-color CSS property sets the background color of an element.


3 Answers

Toggle a class:

function changeClass(){
  document.getElementById('myButton').classList.toggle("the-class");
}

where your CSS is:

.the-class {
    background-color: black;
}

...assuming the element's normal background color is white.

More about classList here. Support is good, but you may need a polyfill in older environments.

Example:

function changeClass() {
  document.getElementById('myButton').classList.toggle("the-class");
}
.the-class {
  background-color: black;
}
<button class="normal" id="myButton" onclick='changeClass()'>Change Colour</button>
like image 189
4 revs, 4 users 53% Avatar answered Oct 10 '22 16:10

4 revs, 4 users 53%


You can use classList.toggle()

document.querySelector('#myButton').addEventListener('click',e => {
  e.target.classList.toggle('black')

})
.black{
  background:black
}
<button class="normal" id="myButton">Change Colour</button>
like image 20
Maheer Ali Avatar answered Oct 10 '22 16:10

Maheer Ali


Use something like classList.toggle()

function switchColor(){
  document.getElementById("resultDiv").classList.toggle("toggle")
}
.element {
  height: 100px;
  width: 100px;
  background-color: red;
}

.element.toggle{
  background-color: blue !important;
}
<button onclick="switchColor()">Click me</button>
<div id="resultDiv" class="element toggle"></div>
like image 2
MauriceNino Avatar answered Oct 10 '22 18:10

MauriceNino