sophiamarinara
sophiamarinara

Reputation: 25

Change background color on click and drag

I'm trying to create a website where the background color changes as you click and drag it. The problem is that the background color does update in my code, but it doesn't have that nice smooth consistently smooth gradient effect. It just jumps from color to color as you drag.

In this code the effect I want is achieved by the mousemove event listener:

document.addEventListener('mousemove', function(event) {
  var width = window.innerWidth / 255
  var height = window.innerHeight / 255
  var xValue = event.clientX / width;
  var yValue = event.clientY / height;
  document.getElementById("bg").style.backgroundColor = 'rgb(' + yValue + ',' + yValue + ',' + xValue + ')';
});
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: white;
  height: 100vh;
  width: 100%;
}
<body id="bg">
  <div></div>
</body>

Upvotes: 1

Views: 1774

Answers (2)

marzelin
marzelin

Reputation: 11600

Add css transition if you want smooth color change:

document.addEventListener('click', function(event) {
  var xValue = Math.floor(Math.random() * 256);
  var yValue = Math.floor(Math.random() * 256);
  document.getElementById("bg").style.backgroundColor = 'rgb(' + yValue + ',' + yValue + ',' + xValue + ')';
});
* {
  padding: 0;
  margin: 0;
}

body {
  background-color: white;
  transition: 500ms background;
  height: 100vh;
  width: 100%;
}
<body id="bg">
  <div></div>
</body>

Upvotes: 1

thank_for_this
thank_for_this

Reputation: 55

According to this page you can't transition a background gradient using CSS. He provides a possible solution to achieve that effect with the help of a pseudo-element and an opacity transform instead.

.gradient {
  position: relative;
  background-image: linear-gradient(
    to right,
    hsl(211, 100%, 50%),
    hsl(179, 100%, 30%)
  );
  z-index: 1;
  height: 100px;
}

.gradient::before {
  position: absolute;
  content: "";
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: linear-gradient(
    to bottom,
    hsl(344, 100%, 50%),
    hsl(31, 100%, 40%)
  );
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}

.gradient:hover::before {
  opacity: 1;
}
<div class="gradient"><a href="#">test to verify content remains visible & on top</a></div>
Hover over the element above to fade the background gradient.

<!-- Full write-up at http://keithjgrant.com/posts/2017/07/transitioning-gradients/ --

Upvotes: 1

Related Questions