JavaScript - Allowing a variable to change the background colour - javascript

i was wondering if there was a way that i could have
document.body.style.backgroundColor = a variable <---something like that
so that when the variable is changed it would set the background colour to the set the colour that is set by the variable
IT has to be javascript, so keep the html to a minimum

var bg= "red"
document.body.style.backgroundColor = bg;
you can change the value with the help of textbox and assign that value to bg variable

No, you can't. There's no event raised when a variable is changed, so when you change the variable, you'll also have to re-run your code setting the backgroundColor.
You could do it with an object property in ES5+ (all modern browsers; not IE8):
var o = {};
Object.defineProperty(o, "bg", {
set: function(value) {
document.body.style.backgroundColor = value;
},
get: function() {
return document.body.style.backgroundColor;
}
});
Now,
o.bg = "green";
changes the background color to green.
Live Example:
var o = {};
Object.defineProperty(o, "bg", {
set: function(value) {
document.body.style.backgroundColor = value;
},
get: function() {
return document.body.style.backgroundColor;
}
});
var colors = ["green", "blue", "yellow"];
var index = 0;
var stopAt = Date.now() + 6000;
tick();
function tick() {
console.log("Setting " + colors[index]);
o.bg = colors[index];
index = (index + 1) % colors.length;
if (Date.now() < stopAt) {
setTimeout(tick, 1000);
}
}
<p>Testing 1 2 3</p>

You can have color values in a select list or can be given through input box. And on that you can bind 'onChnage' event and get that value in a variable and assign that variable to background color property.
Thanks

Easiest code to change background color:
<body>
<script type="text/javascript">
function ZishanAdThandarGreen()
{
document.getElementById("results_container_Zishan").innerHTML = 'Green';
document.getElementById("color").innerHTML = '<!-- body, html {font-family:Tahoma, Times, Times;width:100%;margin:0;padding:0;text-align:center;background:green;} -->';
}
function ZishanAdThandarBlue()
{
document.getElementById("results_container_Zishan").innerHTML = 'Blue';
document.getElementById("color").innerHTML = '<!-- body, html {font-family:Tahoma, Times, Times;width:100%;margin:0;padding:0;text-align:center;background:Blue;} -->';
}
function ZishanAdThandarGrey()
{
document.getElementById("results_container_Zishan").innerHTML = 'grey';
document.getElementById("color").innerHTML = '<!-- body, html {font-family:Tahoma, Times, Times;width:100%;margin:0;padding:0;text-align:center;background:Grey;} -->';
}
</script>
<style type="text/css" id="color">
<!--
body, html {font-family:Tahoma, Times, Times;width:100%;margin:0;padding:0;text-align:center;background:red;}
-->
</style>
<h2>Background Color script by ZishanAdThandar</h2><br>
Current Color:<div id="results_container_Zishan">Red</div>
<button id="download-json" class="btn" style="align:right;"onclick="return ZishanAdThandarGreen()">Green</button>
<button id="download-json" class="btn" style="align:right;"onclick="return ZishanAdThandarBlue()">Blue</button>
<button id="download-json" class="btn" style="align:right;"onclick="return ZishanAdThandarGrey()">Grey</button>
<br>
</body>

Related

backgroundColor change

I want to change the background colour of header(h1) whenever I click on the page.
Here is my code:
document.addEventListener('click', func);
function func(){
var mainHeading = document.querySelector('h1');
var colors = ['cyan', 'black', 'brown'];
for(let b = 0; b <= colors.length; b++){
mainHeading.style.backgroundColor = colors[b];
}
}
You shouldn't use a for loop for that.
Simply keep track of which color you're currently at with a variable :
let color = 0; // Variable to keep track of the color
let colors = ['cyan', 'black', 'brown'];
document.addEventListener('click', func);
function func() {
let mainHeading = document.querySelector('h1');
color = color < colors.length - 1 ? color+1 : 0; //Increment your color or reset it
mainHeading.style.backgroundColor = colors[color];
}
<h1>Test</h1>
You keep looping thru all colours in the array with every click
Instead, you need to keep track of the last colour used and updated it with every event.
Also, you do not need to declare the array of colours every time the event is handled. You can just declare it once (outside the handler) and use it many times.
Something along the lines of:
var currentColorIndex = 0;
var colors = ['cyan', 'black', 'brown'];
document.addEventListener('click', func);
function func() {
var mainHeading = document.querySelector('h1');
// reset color
if (currentColorIndex >= colors.length) {
currentColorIndex = 0;
}
mainHeading.style.backgroundColor = colors[currentColorIndex];
currentColorIndex++;
}
<h1>Title</h1>
You need to save the state of the color. Otherwise, your for loop will always set the color to the last element
document.addEventListener('click', func);
function func(){
var colors = ['cyan', 'black', 'brown'];
var idx = ((this.idx ? this.idx : 0) + 1) % colors.lengh;
this.idx = idx;
var mainHeading = document.querySelector('h1');
mainHeading.style.backgroundColor = colors[idx];
}
}

Background Color Change onload JavaScript+Html

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);
});

How to set CSS value with JavaScript?

I want to change the background color of an HTML element whose ID is foo. I have this code at present:
var hexcode = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
// this chooses a random value from the array hexcode
var ranval = function() {
return hexcode[Math.floor(Math.random()*hexcode.length)];
}
// six ranval() are put together to get color
var colorname = "#" + ranval() + ranval() + ranval() + ranval() + ranval() + ranval();
// trying to put the value on the background of element with "foo" ID.
document.getElementById("foo").style.color = colorname;
This code is throwing this error:
Uncaught TypeError: Cannot read property 'style' of null
I'm sure that ID foo exists.
Your error occurs because you're trying to access your element before the DOM is ready. Wait for the window to load before accessing it:
// Credit: http://paulirish.com/2009/random-hex-color-code-snippets/
function random_color() {
return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6);
}
window.onload = function() {
document.getElementById("foo").style.backgroundColor = random_color();
};
Demo: http://jsfiddle.net/Blender/xQure/1/
The simple way to fix your code is:
var random_color = function() {
function randomHex() {
return Math.floor(Math.random() * 15).toString(16);
}
var str = '#';
for(var i = 6; i--;) {
str += randomHex();
}
return str;
}
window.onload = function() {
// For your body background color
document.body.style.backgroundColor = random_color();
// For your foo element TEXT color
document.getElementById("foo").style.color = random_color();
// For your foo element BACKGROUND color
document.getElementById("foo").style.backgroundColor = random_color();
};

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);
​

In Javascript how can I set rgba without specifying the rgb?

I have an HTML element whose background colour is set with rgba()
<div style="background-color: rgba(2,100,100,0);"> </div>
Then I have a timer that makes the background slowly fade in by changing the opacity value of the element in javascript
myEle.style.backgroundColor = "rgba(x,x,x,0.1)"; // I have to know the rgb values to update the alpha value
Is there a way to set the a value of rgba() without changing/knowing the rgb values?
Maybe I can do something like this?
var r = myEle.style.r;
var g = myEle.style.g;
var b = myEle.style.b;
myEle.style.backgroundColor = "rgba("+r+","+g+","+b+",0.1)";
You got the string, replace whatever
var oldCss = 'rgba(1,1,1,0.3)',
newOpacity = '0.5',
newCss = oldCss.replace(/[^,]+(?=\))/, newOpacity);
console.log(oldCss, "replaced with", newCss);
After some playing around, and the discovery of getComputedStyle, I have put together this.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#element {
background-color: rgb(10,10,10);
background-color: rgba(10,10,10,1);
}
</style>
<script type="text/javascript">
HTMLElement.prototype.alpha = function(a) {
current_color = getComputedStyle(this).getPropertyValue("background-color");
match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color)
a = a > 1 ? (a / 100) : a;
this.style.backgroundColor = "rgba(" + [match[1],match[2],match[3],a].join(',') +")";
}
</script>
</head>
<body>
<div id="element">
This is some content.
</div>
<script type="text/javascript">
e = document.getElementById('element');
e.alpha(20);
</script>
</body>
</html>
Make sure you define in your css your values, and cascade because RGBA is CSS3.
Also see that you can pass in a number >1 for alpha and it will divide by 100 for you (I hate working with decimals when thinking percentages).
Enjoy!
I had do this too but ended up writing something a little more specific. I put it in a jQuery plugin that accepts a min and max opacity:
$.fn.setAlpha = function ( options ) {
var settings = $.extend({
alpha: 0.5,
min: 0,
max: 1
}, options );
return this.each(function() {
var color = $(this).css('background-color');
if (color.substring(0,4) === 'rgba') {
var a;
if (settings.alpha <= settings.min) {
a = settings.min;
} else if (settings.alpha >= settings.max) {
a = settings.max;
} else {
a = settings.alpha;
}
var rgba = color.replace(/[^,]+(?=\))/, a);
$(this).css('background-color', rgba);
}
});
}
$.fn.getAlpha = function () {
var color = this.css('background-color');
if (color.substring(0,4) === 'rgba') {
var alpha = color.split(',');
alpha = alpha[alpha.length - 1].trim();
alpha = alpha.substring(0, alpha.indexOf(")"));
return alpha;
} else {
return 1;
}
}
then you use them to do something like this to set a div to transparent and fade it to its original opacity as you scroll down:
//get original opacity
var originalOpacity = $('#myDiv').getAlpha();
//set new opacity
//it will be 0 at the top of the page
var newOpacity = $(window).scrollTop()/500;
$('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
//on scroll fade new opacity to originalOpacity at 500px down
$(window).scroll( function() {
var newOpacity = $(window).scrollTop()/500;
$('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
}
Does this help?
http://www.phpied.com/rgb-color-parser-in-javascript/
This may help in addition.
Convert RGBA color to RGB
You could also use elem.style.opacity=0.5 or in html style="opacity:0.5". It is important to note that the child nodes will fade too.

Categories

Resources