Search code examples
javascriptbuttonrandomcolorslinear-gradients

how do i write a code for a button to generate random background color gradients


i want to add a button that generates random linear-gradients at the background. The code below generates linear gradients when i click on one button or the other.

var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var gradient = document.querySelector("body");
var css=document.querySelector("h3");
var random = document.getElementById("random")

css.textContent = gradient.style.background  = "linear-gradient(to right," + color1.value + "," + color2.value +")"; 

function setBackground(){
    gradient.style.background = "linear-gradient(to right," + 
    color1.value + "," + color2.value +")";
    css.textContent = gradient.style.background + ";"

}
color1.addEventListener("input", setBackground);

color2.addEventListener("input", setBackground);



Solution

  • The following snippet should do what you are trying to achieve. Please feel free to ask if there is something that is not clear.

    const body = document.getElementsByTagName('BODY')[0];
    const button = document.getElementsByTagName('BUTTON')[0];
    
    function changeBackground(){
      body.style.background = `linear-gradient(to right,${getRandomHEXColor()},${getRandomHEXColor()})`;
    }
    
    function getRandomHEXColor() {
      const SEED = '0123456789abcdef';
      let output = '#';
      while (output.length < 7) {
        output += SEED[Math.floor(Math.random() * SEED.length)];
      }
      return output;
    }
    
    button.addEventListener("click", changeBackground);
    <html>
      <body>
        <button>CHANGE BACKGROUD</button>
      </body>
    </html>