Background Color Change onload JavaScript+Html - javascript

I am attempting to write my own website, however I had an idea to have an Array of background colors that the site would change to at random (but not repeating the same color back to back) every time the page is loaded / refreshed. I remember doing something very similar to this when I was in school but I just can't quite remember how it was done.
This is what I have so far, I have been fiddling with this for about a day and just can't quite figure out what I am missing.
Any assistance would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
<!--
var color = new Array();
color[0] = "#CC99FF";
color[1] = "#FF99CC";
color[2] = "#FF9999";
color[3] = "#FFCC99";
color[4] = "#FFFF99";
color[5] = "#CCFF99";
color[6] = "#99FF99";
color[7] = "#99FFCC";
color[8] = "#66FFFF";
color[9] = "#66CCFF";
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.backgroundColor = color[randomColor];
}
--!>
</script>
</head>
<body onload="changeColor()">
</body>
</html>

I noticed that your question had a second part, which is to not repeat the same color twice. Since you are doing this on a reload, it becomes a little trickier since you cannot just store the last color in a simple variable.
For this, I decided to utilized localStorage. I leveraged some of the other answers as well that mentioned you need to use the style property on the body element.
Here is a Fiddle of the solution and the code is below:
As mentioned, you need to use the style property to set the background color:
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
Then, you need to keep looking for an index that wasn't used in the last run:
First, I grab the currently stored index, or -1 if it doesn't exist.
var lastColorIndex = localStorage.getItem('lastColorIndex') || -1;
Then set do the loop while the two indices aren't equal or if random color is -1 (this is for on the initial page load). Note that we are using == for a 'truthy' check since localStorage will return a string and Math.random() returns a number;
while(lastColorIndex == randomColor || randomColor === -1)
Finally, set the randomColor value into local storage.
localStorage.setItem('lastColorIndex',randomColor);
All together now:
function changeColor()
{
var lastColorIndex = localStorage.getItem('lastColorIndex') || -1;
var randomColor = -1;
while(lastColorIndex == randomColor || randomColor === -1) {
randomColor = Math.floor(Math.random() * color.length);
console.log('LastIndex: ' + lastColorIndex + ',RandomColor: ' + randomColor);
};
localStorage.setItem('lastColorIndex',randomColor);
//console.log(randomColor);
console.log(color[randomColor]);
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
};

you must access to you body style :
function changeColor() {
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.backgroundColor = color[randomColor];
}

you can change the background color like that
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.background = color[randomColor];
}

You are not accessing the background color property correctly.Use it this way.
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
document.body.style.backgroundColor = color[randomColor]; //THIS IS IMP
}

Have a look at this fiddle (click 'run' several times to simulate reload) :
http://jsfiddle.net/4j61r6go/
function changeColor()
{
var randomColor = Math.floor(Math.random() * color.length);
console.log(color[randomColor]);
document.getElementsByTagName("body")[0].style.backgroundColor=color[randomColor];
};
you should call 'changeColor' in windowor document 'onload'.

I have found a code in a theme hope this will help you
$('.animated-bg').each(function(){
var $this = $(this),
colors = ['#ec008c', '#00bcc3', '#5fb26a', '#fc7331'];
setInterval(function(){
var color = colors.shift();
colors.push(color);
$this.animate({backgroundColor: color}, 2000);
},4000);
});

Related

How do I give each individual div a random background color?

I'm building a website and I want each div on the page to be a random color from the choices below. But once I run the code each of the divs are the same color. Where am I going wrong?
$(document).ready(function(){
var colors = ['red','blue','green','yellow','cyan','orange'];
var new_color = colors[Math.floor(Math.random()*colors.length)];
$('.color-div').css('background-color',new_color);
});
Here is a solution where you loop through all .color-div and set a "random"
color for each.
it uses the .each() method.
Your code was right... but ran only once and applied the color to all elements.
$(document).ready(function(){
var colors = ['red','blue','green','yellow','cyan','orange'];
$('.color-div').each(function(){
var new_color = colors[Math.floor(Math.random()*colors.length)];
$(this).css('background-color',new_color);
});
}); // End ready
div{
height:2em;
width: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-div"></div>
<div class="color-div"></div>
<div class="color-div"></div>
<div class="color-div"></div>
<div class="color-div"></div>
An approach that uses pure Vanilla JavaScript:
Your divs:
<div class="colour-div"></div>
<div class="colour-div"></div>
<div class="colour-div"></div>
<div class="colour-div"></div>
<div class="colour-div"></div>
And the JS:
var colours = ['red','blue','green','yellow','cyan','orange'];
var divs = document.getElementsByClassName("colour-div");
function generateRandomColors() {
var i;
for (i = 0; i < divs.length; i++) {
var newColor = Math.floor(Math.random()*colours.length)
divs[i].style.backgroundColor = colours[newColor];
}
}
The script will continue to function correctly if you:
- Add any number of divs to the colour-div class
- Include any amount of colours to the colours[]
Your code works exactly as expected, assuming you have:
Correctly included jQuery
Got at least one element with a class of color-div
If your code is not working, your problem is most likely that you have not included jQuery. Make sure it is referenced with something like:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a working example:
$(document).ready(function() {
var colors = ['red', 'blue', 'green', 'yellow', 'cyan', 'orange'];
var new_color = colors[Math.floor(Math.random() * colors.length)];
$('.color-div').css('background-color', new_color);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-div">Text</div>
UPDATE
The problem with the above is that the 'random' colour will be the same for each $('.color-div') element, which may not be desired if there's more than one matching element.
If you want each element to have a different random colour, you'll want to make use of .each() to iterate over the elements, and target the elements inside of the loop with $(this). Also note that you'll want to define new_color inside the loop.
This can be seen in the following:
$(document).ready(function() {
var colors = ['red', 'blue', 'green', 'yellow', 'cyan', 'orange'];
$.each($('.color-div'), function() {
var new_color = colors[Math.floor(Math.random() * colors.length)];
$(this).css('background-color', new_color);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-div">Text</div>
<div class="color-div">Text</div>
<div class="color-div">Text</div>
<div class="color-div">Text</div>
Your code uses a random color for all elements. You need to get a random color for each element. This means iteration.
The following code gets a random color for each element:
var colors = ['red','blue','green','yellow','cyan','orange'];
$('.color-div').css('background-color', function() {
var i = Math.floor(Math.random()*colors.length);
var color = colors[i];
colors.splice(i, 1);
return color;
});
The above code makes sure that a color is only used once. If having 2 or more elements with the same color is acceptable, you can remove the colors.splice line. Also note that the code with the splice statement assumes there are not more than 6 .color-div elements.
I would combine #ObsidianAge and #LouysPatriceBessette answers into one and calculate the color like this so is not restricted to your list...
var r = Math.random() * 255;
var g = Math.random() * 255;
var b = Math.random() * 255;
var new_color = 'rgb(' + r + ',' g + ',' + b ')';
Should end up with something like this:
$(document).ready(function() {
$('.color-div').each(function(){
var r = Math.random() * 255;
var g = Math.random() * 255;
var b = Math.random() * 255;
var new_color = 'rgb(' + r + ',' g + ',' + b ')';
$(this).css('background-color',new_color);
});
});
https://jsfiddle.net/xpvt214o/689705/
Edit, just see you said, "From the choices"... sorry, anyway, leave this code here for it may be of use to someone.

Generate a random site colour scheme using JavaScript

I am currently working on a small site and thought it would be quirky if the site adopted a random colour scheme on each visit - meaning each time a user visited the site, they would see a slightly different version.
I have attempted doing this using JavaScript but the site generates a new colour on each page visit...
Any help would be great - if it can be done solely using JS that is?
$(document).ready(function(){
// Generate random colour for the header of the site...
let colours = [
'#F8E71C',
'#1cf8b1',
'#1cb1f8',
'#c21cf8',
'#f81c3a',
];
let randomNumber = Math.floor(Math.random() * colours.length) + 1;
let header = $('.site-head');
let cardColour = $('.card__border');
localStorage.setItem("siteTheme", colours[randomNumber]);
if (localStorage.getItem("siteTheme")) {
header.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
cardColour.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
}
});
Your issue is that you generate a random color and then set it in localStorage, every time.
I refactored your code into functions with an initial check.
$(document).ready(function() {
let header = $('.site-head');
let cardColour = $('.card__border');
if (localStorage.getItem("siteTheme")) {
setColorScheme();
} else {
createColorScheme();
}
function createColorScheme() {
let colours = [
'#F8E71C',
'#1cf8b1',
'#1cb1f8',
'#c21cf8',
'#f81c3a',
];
let randomNumber = Math.floor(Math.random() * colours.length) + 1;
localStorage.setItem("siteTheme", colours[randomNumber]);
setColorScheme();
}
function setColorScheme() {
header.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
cardColour.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
}
});
Note: I think you have an error in the random generator part, sometimes the random color becomes undefined, I think it's because of the + 1.
Why don't you check localStorage before storing another random color sheme?
$(document).ready(function(){
// Generate random colour for the header of the site...
let colours = [
'#F8E71C',
'#1cf8b1',
'#1cb1f8',
'#c21cf8',
'#f81c3a',
];
let header = $('.site-head');
let cardColour = $('.card__border');
if (!localStorage.getItem("siteTheme")) {
let randomNumber = Math.floor(Math.random() * colours.length) + 1;
localStorage.setItem("siteTheme", colours[randomNumber]);
}
header.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
cardColour.css({
backgroundColor: localStorage.getItem("siteTheme"),
});
});

Random array with index

I have a problem I can not solve probably due to exhaustion. In my page I have two boxes in which pressing the "start" button changes the background color randomly without repetition. At first it worked then I changed some things and it no longer works as before. Sometimes I do not make colors appear in the array equal on the two panes. Here is my code
function go(){
var random = Math.floor((Math.random() * colori.length) + 0);
var t = Math.floor((Math.random() * colori.length) + 0);
var sx = document.getElementById("sx");
var dx = document.getElementById("dx");
var btngo = document.getElementById("go");
document.getElementById("scritta").innerHTML = random;
document.getElementById("scrittaU").innerHTML = t;
dx.style.backgroud = colori[random];
sx.style.backgroud = colori[t];
if(random == t){
alert("random:"+random+" " +"t"+t);
alert(colori.splice(random,1));
random = Math.floor((Math.random() * colori.length) + 0);
dx.style.background = colori[t];
sx.style.background = colori[random];
colori.splice(random,1);
colori.splice(t,1);
}
dx.style.background = colori[t];
sx.style.background = colori[random];
colori.splice(random,1);
colori.splice(random-1,1);
btngo.disabled=true;
}
dx.style.backgroud = colori[random];
sx.style.backgroud = colori[t];
Do you mean .background?

How do I keep changing a color with javascript?

I wanted to keep the colors changing on a certain word. Can anyone help me? This is what I have so far:
var myColor = document.getElementById("color");
var colorArray = ["#ffd464", "#2980b9", "#DC143C", "#3CB371", "#DA70D6", "#9400D3"];
var colorIndex = 0;
function changeColor() {
myColor.style.color('color', colorArray[colorIndex]);
colorIndex++;
if (colorIndex >= colorArray.length) {
colorIndex = 0;
}
}
setInterval(changeColor, 5000);
Thank you!
I would give a try this way, dont want to maintain an index:
function changeColor(){
var color = colorArray.shift(); //get the top color from array
colorArray.push(color); //push it to the end to cycle it
myColor.style['color'] = color ; //syntax error here
}
setInterval( changeColor,5000 );
and also
myColor.style.color('color', colorArray[colorIndex]);
should be
myColor.style['color'] = color ;
since color is a property of style attribute of the element and it is not a method.
Fiddle

change background img each time by clicking link

<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
Change
</body>
sorry, i don't get how i exactly should properly integrate code here -hopefully it still worked. what i want to do here: change the background (that works) than add plus one to the background counter so that the next time the link is clicked the next background shows (that doesn't work). it should be quite simple but i couldn't figure it out nevertheless...
Use a static counter that counts from 0 to 3.
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}
There are a couple of issues in your code
backImage = backImage++;
Doesn't increment backImage as you expect. The syntax should be simply backImage++;
Also, to set the background image you need document.body.style.background or document.body.style.backgroundImage = url(...)
Edit
Over and above cycling through the backgrounds via the click handler, if you also need to set the initial background, try something like below, with the initial background set in window.onload.
jsFiddle here
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);
​

Categories

Resources