HatsonBoats58 Woo
HatsonBoats58 Woo

Reputation: 39

How can I let the user choose a background color using hex and css gradients

I would like to make it so that the user can input a hex into one text box and another hex into a different text box. This would then use linear-gradient so that it would gradient the first color to the second color. In the code snippet is an example of what it may produce. I would prefer to only use css and html but can use javascript if neccessary. Thanks to anyone who attempts to solve this problem any bit. I will respond to any questions in case I am being vague.

body {
  background: linear-gradient(to right, #ffb6ce, #ff00ea);
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

Upvotes: 3

Views: 227

Answers (2)

doğukan
doğukan

Reputation: 27381

I created an example.

const body = document.querySelector("body");
const startInput = document.querySelector("#start");
const endInput = document.querySelector("#end");

let startHex = "#fff";
let endHex = "#fff";

let gradient;

function styleBody(){
  gradient = `linear-gradient(to right, ${startHex}, ${endHex})`;
  body.style.background = gradient;
}

startInput.addEventListener("input", () => {
  startHex = event.target.value;
  styleBody();
});

endInput.addEventListener("input", () => {
  endHex = event.target.value;
  styleBody();
});
<input type="color" id="start">
<input type="color" id="end">

Upvotes: 1

Dhaval Jardosh
Dhaval Jardosh

Reputation: 7299

const colorPicker1 = document.querySelector("#picker1");
const colorPicker2 = document.querySelector("#picker2");
var firstColor = '#0F0';
var secondColor = '#F00'

document.body.addEventListener("input", gradientPick);

function gradientPick(event) {
  if(event.target === colorPicker1){
    firstColor = event.target.value;
  }
  
  if(event.target === colorPicker2){
    secondColor = event.target.value;
  }
  document.body.style.background = `linear-gradient(${firstColor}, ${secondColor})`;
  document.body.style.backgroundSize = "contain";
  document.body.style.height = "100vh";
}
<input id="picker1" type="color" value="#ff0000">
<input id="picker2" type="color" value="#00ff00">

Upvotes: 1

Related Questions