Reputation: 3017
I'm looking to just have a simple div fade endlessly between two colors i.e. Blue to red, red to blue, blue to red, etc.
Ideally I'd have a function like this that just takes two colors and the time it takes to fade between them.
toggle_color = function(color1, color2, time) { ... }
I've tried using setInterval and setTimeout to just flop between them, but it's not doing so smoothly (i.e. Fade) or in a loop. Not sure how to do that part. Also not sure that using a delay is the right road to go. Seems like it could be simpler to just be constantly in the state of fading between with a single time value, but again, not sure how.
function toggle_color(color1, color2, cycle_time, wait_time) {
setInterval(function first_color() {
document.body.style.backgroundColor = color1;
setTimeout(change_color, wait_time);
}, cycle_time);
function change_color() {
document.body.style.backgroundColor = color2;
}
Upvotes: 3
Views: 2965
Reputation: 206008
In just a couple of CSS lines:
body{
animation: bodybg 2s 0s linear infinite alternate;
}
@keyframes bodybg{
from {background:red;}
to {background:blue;}
}
Upvotes: 4
Reputation: 1183
I don't know how you could do this well without using CSS transitions, but I believe you can still get what you want. You can dynamically modify the transition time for the background-color animation with JS.
// CSS
body {
-webkit-transition:background-color 1s ease;
-moz-transition:background-color 1s ease;
-o-transition:background-color 1s ease;
transition:background-color .1s ease;
}
// JS
var id = toggle_color('red', 'blue', 5000);
function toggle_color(color1, color2, time) {
var $selector = document.querySelector('body');
setTransitionDurations($selector, time)
$selector.style.backgroundColor = $selector.style.backgroundColor === color1 ? color2 : color1;
var intervalId = setInterval(function() {
$selector.style.backgroundColor = $selector.style.backgroundColor === color1 ? color2 : color1;
}, time);
return intervalId;
}
function getStringFromMs(ms) {
// convert ms to string
// i.e. 1000 => '1ms'
return ms + 'ms';
}
function setTransitionDurations($selector, ms) {
var transitionSeconds = getStringFromMs(ms);
// you need to set the transition for
// each browser for max compatibility
var prefixes = ['-webkit', '-o', '-moz'];
prefixes.forEach(function(prefix) {
$selector.style.setProperty(prefix + '-transition-duration', transitionSeconds);
})
$selector.style.transitionDuration = transitionSeconds;
}
Check out this jsfiddle to mess around: https://jsfiddle.net/dwLL9yy4/8/. Note a couple things. If you are dynamically changing the transition, you will want to make sure to update the transition for each browser. Note, transitions are only supported in IE10 and up. Also, the transition expects the time in the form '1s' or '1000ms'. For more details on transitions, check out https://developer.mozilla.org/en-US/docs/Web/CSS/transition
Upvotes: 1