'Change background colour and text colour on click
What I have been trying -unsuccessfully- to achieve is to change the colour of the background and the text by clicking one <a> element, randomly rotating amongst several colour combinations.
My default colours are:
color: #1B1725;
background-color: #A30B37;
I would like to use, at least, three colour combinations more (for the sake of this example, those three other combinations can be basic colours).
Edit for further development:
I need just one button that toggles between three colour combinations (not random colours).
What I have tried so far:
function changeColor(combo) {
if(combo=="combo1"){
document.body.style.backgroundColor = "#FEFAE0";
document.body.style.color = "red";
}else if(combo=="combo1"){
document.body.style.backgroundColor = "blue";
document.body.style.color = "white";
}
}
Using this, it changes from the default colours to the "combo1" colours. I would need that button to keep changing on click.
Solution 1:[1]
You can generate random colors like this:
// Generate random colors
var bg = Math.floor(Math.random()*16777215).toString(16);
var text = Math.floor(Math.random()*16777215).toString(16);
OR
// To generate predefined colors
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var colors = ["000000","FEFEFE","FFFAAA"];
var bg = colors[getRandomInt(colors.length)];
var text = colors[getRandomInt(colors.length)];
Finally
var div = document.getElementById('mydiv');
var a= document.getElementById('atagid');
a.onclick = function() {
div.style.backgroundColor = "#"+bg;
div.style.color= "#"+text;
}
Solution 2:[2]
Here is sandbox example: https://codesandbox.io/s/currying-cherry-nt80k?file=/index.html
function getColorChange(){
var x = 1
var a = "black"
var intervalID = setInterval(function () {
document.getElementById("changeColor").style.backgroundColor = a;
if (x == 1) {
a = "green"
}
if (x == 2 ) {
a="red"
}
if (++x === 4) {
window.clearInterval(intervalID);
}
}, 5000);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Tyler2P |
