I've set up a web page which changes the background color of the body after every 2 seconds. What I've been struggling with is how to integrate transition effect into the setInterval method. I want the new colors to appear with a fade effect, just like the transition property does in CSS. How can I achieve this effect for these changing/switching background colors?
Here's my code:
var startButton = document.getElementById("startButton");
var body = document.getElementById("body");
// Click Event Listener
startButton.addEventListener("click", function() {
setInterval(function() {
body.style.backgroundColor = generateRandomColors();
}, 2000);
});
// GENERATE Random Colors
function generateRandomColors() {
var arr = [];
arr.push(pickRandomColor());
return arr;
}
// PICK Random Color
function pickRandomColor() {
// Red
var r = Math.floor(Math.random() * 256);
// Green
var g = Math.floor(Math.random() * 256);
// Blue
var b = Math.floor(Math.random() * 256);
// RGB
var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
return rgb;
}
<html>
<body id="body">
<button id="startButton">Start</button>
</body>
</html>
Set the transition property specifying which property you want to transition and how long it will take.
var startButton = document.getElementById("startButton");
var body = document.getElementById("body");
// Click Event Listener
startButton.addEventListener("click", function() {
setInterval(function() {
body.style.backgroundColor = generateRandomColors();
}, 2000);
});
// GENERATE Random Colors
function generateRandomColors() {
var arr = [];
arr.push(pickRandomColor());
return arr;
}
// PICK Random Color
function pickRandomColor() {
// Red
var r = Math.floor(Math.random() * 256);
// Green
var g = Math.floor(Math.random() * 256);
// Blue
var b = Math.floor(Math.random() * 256);
// RGB
var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
return rgb;
}
body { transition: background-color 2s; }
<html>
<body id="body">
<button id="startButton">Start</button>
</body>
</html>
Related
var color2;
var color3;
var color1;
var interval;
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function ColorEverySecond(id){
interval = setInterval(changeColor(id),500);
}
function stopColorEverySecond(){
clearInterval(interval)
}
function changeColor(id){
color1 = getRandomInt(255);
color2 = getRandomInt(255);
color3 = getRandomInt(255);
document.getElementById(id).style = "color: rgb(" + color1 + ", " + color2 + ", " + color3 + ")";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id = "rainbow" onmouseover="ColorEverySecond(id)" onmouseout="stopColorEverySecond()">
When you hover I should change colors every 500 milliseconds, but instead I just change everytime you hover.
</h1>
</body>
</html>
For some reason it won't change color every 500 milliseconds and instead only changes once when you hover. I noticed that it only activates the function 'changeColor' once in the interval and then it stops.
I tried to replicate solutions from this post but they did not work for me. I think it has to with the 'changeColor' function but I do not see the problem. How do I fix it?
You are calling the function instead of passing it as argument for the setInterval. Use this syntax:
var color2;
var color3;
var color1;
var interval;
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function ColorEverySecond(id) {
interval = setInterval(function() {
changeColor(id)
}, 500);
// also right away
changeColor(id)
}
function stopColorEverySecond() {
clearInterval(interval)
}
function changeColor(id) {
color1 = getRandomInt(255);
color2 = getRandomInt(255);
color3 = getRandomInt(255);
document.getElementById(id).style = "color: rgb(" + color1 + ", " + color2 + ", " + color3 + ")";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="rainbow" onmouseover="ColorEverySecond(id)" onmouseout="stopColorEverySecond()">
When you hover I should change colors every 500 milliseconds, but instead I just change everytime you hover.
</h1>
</body>
</html>
You faced this problem because of setInterval. setInterval receives a callback. But directly call the changeColor function. As you have to call the changeColor function here that's why you have to use a callback here. Hope you understand.
var color2;
var color3;
var color1;
var interval;
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function ColorEverySecond(id){
interval = setInterval(()=> changeColor(id), 500);
}
function stopColorEverySecond(){
clearInterval(interval)
}
function changeColor(id){
color1 = getRandomInt(255);
color2 = getRandomInt(255);
color3 = getRandomInt(255);
document.getElementById(id).style = "color: rgb(" + color1 + ", " + color2 + ", " + color3 + ")";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id = "rainbow" onmouseover="ColorEverySecond(id)" onmouseout="stopColorEverySecond()">
When you hover I should change colors every 500 milliseconds, but instead I just change everytime you hover.
</h1>
</body>
</html>
var color2;
var color3;
var color1;
var interval;
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function ColorEverySecond(id){
interval = setInterval(changeColor,500,id);
}
function stopColorEverySecond(){
clearInterval(interval)
}
function changeColor(id){
color1 = getRandomInt(255);
color2 = getRandomInt(255);
color3 = getRandomInt(255);
document.getElementById(id).style = "color: rgb(" + color1 + ", " + color2 + ", " + color3 + ")";
}
<!DOCTYPE html> <html>
<head>
</head> <body>
<h1 id = "rainbow" onmouseover="ColorEverySecond(id)" onmouseout="stopColorEverySecond()"> When you hover I change colors every 500 milliseconds.
</h1>
</body>
</html>
The Answer
Right now I'm trying to develop a very simple button that changes the background color of the whole webpage. Here is the code I have
var mybutton = document.querySelector('button');
var myBack = document.querySelector("body");
var isRand = false;
var ranNumber1 = Math.floor(Math.random() * 256);
var ranNumber2 = Math.floor(Math.random() * 256);
var ranNumber3 = Math.floor(Math.random() * 256);
var RanRGB = "rgb(" + ranNumber1 + "," + ranNumber2 + "," + ranNumber3 + ")";
mybutton.addEventListener("click", function() {
if (isRand) {
myBack.style.backgroundColor = "white";
isRand = false;
} else {
myBack.style.backgroundColor = RanRGB
isRand = true;
}
});
<!DOCTYPE html>
<html>
<head>
<title>toggle</title>
</head>
<body>
<div>
<button>click here!</button>
</div>
<script type="text/javascript" src="togglescript.js"></script>
</body>
</html>
When this webpage loads and I click the button, the background color changes to a random color from white. Then if i click again it turn white again. This is what I want. However, then I want to be able to click the button again and change the color to a new random color. Currently it just changes it background back to the color it generated originally. How do I reset the background color?
Move the color generation into your function.
var mybutton = document.querySelector('button');
var myBack = document.querySelector("body");
var isRand = false;
mybutton.addEventListener("click", function() {
var ranNumber1 = Math.floor(Math.random() * 256);
var ranNumber2 = Math.floor(Math.random() * 256);
var ranNumber3 = Math.floor(Math.random() * 256);
var RanRGB = "rgb(" + ranNumber1 + "," + ranNumber2 + "," + ranNumber3 + ")";
if (isRand) {
myBack.style.backgroundColor = "white";
isRand = false;
} else {
myBack.style.backgroundColor = RanRGB
isRand = true;
}
});
I've got the following piece of code and I'd like the 'rect' element (which is a canvas element) transition the colour from black to white. It doesn't. Please advise:
var background = document.getElementById("rect");
setInterval(function() {
for (i=0;i<255;i++) {
background.style.backgroundColor = 'rgb(' + [i, i, i].join(',') + ')';
}
}, 900);
By changing the colors in a loop, you're effectively doing it all at once. Instead, do one change per interval callback:
var background = document.getElementById("rect");
var i = 0;
var timer = setInterval(function() {
background.style.backgroundColor = 'rgb(' + [i, i, i].join(',') + ')';
if (++i > 255) {
clearInterval(timer);
}
}, 900);
Note that at 900ms per change and 255 changes, that will take a long time to complete, so you may need to adjust the interval.
Here's an example using an interval of 20ms:
var background = document.getElementById("rect");
var i = 0;
var timer = setInterval(function() {
background.style.backgroundColor = 'rgb(' + [i, i, i].join(',') + ')';
if (++i > 255) {
clearInterval(timer);
}
}, 20);
#rect {
height: 4em;
}
<div id="rect"></div>
I'm trying to have it so that each square is a different color when the user hovers over it once the "randomize" button is clicked. Nothing changes when I chose the randomize function. Here's my code:
function randomSetup(numOfSquares){
var numSquares = numOfSquares;
var squareSide = 500 / numSquares;
var totalSquares = numSquares * numSquares;
for(var rows = 0; rows < totalSquares; rows++){
$('<div class="gridSquare"></div>').appendTo('.container')
}
var colors = randomColor();
$('.container').on('mouseenter', '.gridSquare', function(){
$(this).css('background-color', 'rgb(colors,colors,colors)');
});
$('.gridSquare').width(squareSide);
$('.gridSquare').height(squareSide);
}
function randomColor(){
return Math.random() * (255 - 0) + 1;
}
Fiddle
This is invalid:
'rgb(colors,colors,colors)'
Try this:
$('.container').on('mouseenter', '.gridSquare', function(){
var red = randomColor();
var green = randomColor();
var blue = randomColor();
$(this).css('background-color', 'rgb('+red+','+green+','+blue+')');
});
You also need to round your random number:
function randomColor(){
return Math.round(Math.random() * (255 - 0) + 1);
}
http://jsfiddle.net/oLonz7c0/21/
Here you go: http://jsfiddle.net/oLonz7c0/7/
Trippy.
Regenerate the random colors inside the event handler so each square is a different color.
$('.container').on('mouseenter', '.gridSquare', function(){
var colors = [];
colors[0] = Math.round(randomColor());
colors[1] = Math.round(randomColor());
colors[2] = Math.round(randomColor());
$(this).css('background-color', 'rgb('+colors[0]+','+colors[1]+','+colors[2]+')');
});
You can try some thing like
function randomColor(){
var colors = ["#CCCCCC","#333333","#990099"];
var rand = Math.floor(Math.random()*colors.length);
//return Math.random() * (255 - 0) + 1;
return colors[rand];
}
And
var colors ='';
$('.container').on('mouseenter', '.gridSquare', function(){
colors = randomColor();
$(this).css('background-color',colors );
});
Fiddle : http://jsfiddle.net/oLonz7c0/14/
So I need function like this one, -link- but just to move text up, not left. How to achieve this?
So, this is code that moves text left:
//Text fade
var bgcolor;
var fcolor;
var heading;
//Number of steps to fade
var steps;
var colors;
var color = 0;
var step = 1;
var interval1;
var interval2;
//fade: fader function
// Fade from backcolor to forecolor in specified number of steps
function fade(headingtext,backcolor,forecolor,numsteps) {
if (color == 0) {
steps = numsteps;
heading = "<font color='{COLOR}'>"+headingtext+"</strong></font>";
bgcolor = backcolor;
fcolor = forecolor;
colors = new Array(steps);
getFadeColors(bgcolor,fcolor,colors);
}
// insert fader color into message
var text_out = heading.replace("{COLOR}", colors[color]);
// write the message to the document
document.getElementById("fader").innerHTML = text_out;
// select next fader color
color += step;
if (color >= steps) clearInterval(interval1);
}
//getFadeColors: fills colors, using predefined Array, with color hex strings fading from ColorA to ColorB
//Note: Colors.length equals the number of steps to fade
function getFadeColors(ColorA, ColorB, Colors) {
len = Colors.length;
//Strip '#' from colors if present
if (ColorA.charAt(0)=='#') ColorA = ColorA.substring(1);
if (ColorB.charAt(0)=='#') ColorB = ColorB.substring(1);
//Substract red green and blue components from hex string
var r = HexToInt(ColorA.substring(0,2));
var g = HexToInt(ColorA.substring(2,4));
var b = HexToInt(ColorA.substring(4,6));
var r2 = HexToInt(ColorB.substring(0,2));
var g2 = HexToInt(ColorB.substring(2,4));
var b2 = HexToInt(ColorB.substring(4,6));
// calculate size of step for each color component
var rStep = Math.round((r2 - r) / len);
var gStep = Math.round((g2 - g) / len);
var bStep = Math.round((b2 - b) / len);
// fill Colors array with fader colors
for (i = 0; i < len-1; i++) {
Colors[i] = "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);
r += rStep;
g += gStep;
b += bStep;
}
Colors[len-1] = ColorB; // make sure we finish exactly at ColorB
}
//IntToHex: converts integers between 0 - 255 into a two digit hex string.
function IntToHex(n) {
var result = n.toString(16);
if (result.length==1) result = "0"+result;
return result;
}
//HexToInt: converts two digit hex strings into integer.
function HexToInt(hex) {
return parseInt(hex, 16);
}
var startwidth = 0;
//scroll: Make the text scroll using the marginLeft element of the div container
function scroll(startw) {
if (startwidth == 0) {
startwidth=startw;
}
document.getElementById("fader").style.marginLeft = startwidth + "px";
if (startwidth > 1) {
startwidth -= 1;
} else {
clearInterval(interval2);
}
}
function fadeandscroll(txt,color1,color2,numsteps,fademilli,containerwidth,scrollmilli) {
interval1 = setInterval("fade('"+txt+"','"+color1+"','"+color2+"',"+numsteps+")",fademilli);
interval2 = setInterval("scroll("+containerwidth+")",scrollmilli);
}
Something like this seems to do what you want, but jQuery would have been easier.
Demo: Vertical Marquee Demo
window.document.addEventListener("DOMContentLoaded", function()
{
var elm = window.document.querySelectorAll("#display span")[0], height = elm.parentNode.offsetHeight;
elm.style.position = "relative";
elm.style.top = "0px";
var timer = setInterval(function()
{
var top = Number(elm.style.top.replace(/[^\d\-]/g, ''));
top = top > -height ? top - 1 : height;
elm.style.top = top + "px";
}, 50);
/*
* If you want to stop scrolling, call clearInterval(timer);
*
* Example set to stop when clicked.
*/
elm.addEventListener("click", function()
{
clearInterval(timer);
}, false);
}, false);