Home > Enterprise >  Change background colour and text colour on click
Change background colour and text colour on click

Time:02-02

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).

CodePudding user response:

You can generate random colors like this:

    var bg = Math.floor(Math.random()*16777215).toString(16);
    var text = Math.floor(Math.random()*16777215).toString(16);
    var div = document.getElementById('mydiv');
    var a= document.getElementById('atagid');
    a.onclick = function() {
      div.style.backgroundColor = "#" bg;
      div.style.color= "#" text;
    }

CodePudding user response:

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);
}
  •  Tags:  
  • Related