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.
Related
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>
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);
});
i am working on a small application (phonegap) that scrolls a page of a book when the users pushed the audio-button to listen to the text at the same time. The general idea :-)
I have looked into the Marquee version, what works so far but it has some strange behaviour:
<marquee behavior="scroll" height="100%" vspace="0%" direction="up" id="mymarquee" scrollamount="3" scolldelay="1000" loop="1"> TEXT HERE </marquee>
with the "id="mymarquee" connected to the audio play button. This works but not recommanded as they say. Better to use a javascript version. So i found a cool version so far on the web, but it goes from the right to the left. Now i am not the best programmer in the world so i was wondering if someone could help adjust the script below so we can add a direction to it. This way the script would be multi-functional (for others as well) since i only need a scroll from top to bottom.
Here is the HTML part:
<script src="js/slideandfade.js" type="text/javascript"></script>
<DIV ID="fader" STYLE="text-align:right;"></DIV>
<SCRIPT TYPE="text/javascript">
fadeandscroll('TEXT HERE', '#676F77', '#DFF5FF', 40, 70, 250, 10);
</SCRIPT>
And this is the slideandfade.js
//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);
}
I want to animate (transition) from 1 color to another in raw javascript.
I dont want to use any framework (jquery, mootools) or css3. plain raw javascript.
I have been really having trouble to do this, can someone help me out ? :)
maybe something like this:
lerp = function(a, b, u) {
return (1 - u) * a + u * b;
};
fade = function(element, property, start, end, duration) {
var interval = 10;
var steps = duration / interval;
var step_u = 1.0 / steps;
var u = 0.0;
var theInterval = setInterval(function() {
if (u >= 1.0) {
clearInterval(theInterval);
}
var r = Math.round(lerp(start.r, end.r, u));
var g = Math.round(lerp(start.g, end.g, u));
var b = Math.round(lerp(start.b, end.b, u));
var colorname = 'rgb(' + r + ',' + g + ',' + b + ')';
el.style.setProperty(property, colorname);
u += step_u;
}, interval);
};
You can play around an try it out as a jsfiddle or check out the full working example below. You might want to improve this by using HSL/HSV colors, which gives you a prettier transition, but i'll leave that up to you.
<html>
<head>
<title>Fade</title>
<style type="text/css">
#box {
width: 100px;
height: 100px;
background-color: rgb(255,0,0);
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript" charset="utf-8">
// linear interpolation between two values a and b
// u controls amount of a/b and is in range [0.0,1.0]
lerp = function(a,b,u) {
return (1-u) * a + u * b;
};
fade = function(element, property, start, end, duration) {
var interval = 10;
var steps = duration/interval;
var step_u = 1.0/steps;
var u = 0.0;
var theInterval = setInterval(function(){
if (u >= 1.0){ clearInterval(theInterval) }
var r = parseInt(lerp(start.r, end.r, u));
var g = parseInt(lerp(start.g, end.g, u));
var b = parseInt(lerp(start.b, end.b, u));
var colorname = 'rgb('+r+','+g+','+b+')';
el.style.setProperty(property, colorname);
u += step_u;
}, interval);
};
// in action
el = document.getElementById('box'); // your element
property = 'background-color'; // fading property
startColor = {r:255, g: 0, b: 0}; // red
endColor = {r: 0, g:128, b:128}; // dark turquoise
fade(el,'background-color',startColor,endColor,1000);
// fade back after 2 secs
setTimeout(function(){
fade(el,'background-color',endColor,startColor,1000);
},2000);
</script>
</body>
</html>
Here is also my solution:
<html><head>
<script type="text/javascript">
<!--
function animate(id,color0,color1,duration){
//public attributes
this.elem = document.getElementById(id);
//private attributes
var r0= parseInt(color0.substring(0,2),16);
var g0= parseInt(color0.substring(2,4),16);
var b0= parseInt(color0.substring(4,6),16);
var r1= parseInt(color1.substring(0,2),16);
var g1= parseInt(color1.substring(2,4),16);
var b1= parseInt(color1.substring(4,6),16);
var wait = 100; //100ms
var steps = duration/wait;
var rstep = (r1 - r0) / (steps);
var gstep = (g1 - g0) / (steps);
var bstep = (b1 - b0) / (steps);
var self = this;
//public functions
this.step = function() {
steps--;
if ( steps>0 ) {
r0 = Math.floor(r0 + rstep);
g0 = Math.floor(g0 + gstep);
b0 = Math.floor(b0 + bstep);
elem.style.backgroundColor = 'rgb('+r0+','+g0+','+b0+')';
//alert(steps + ' ; ' + elem.style.backgroundColor);
window.setTimeout(function(){self.step();}, wait);
} else {
elem.style.backgroundColor = '#'+color1;
}
}
step();
//alert(this.r0);
}
//-->
</script>
</head><body>
<div id="anim" style="width:100px; height:100px; background-color:#ff0000"></div>
<input type="button" onclick="animate('anim','1122ff','ff2211',1000)" value="test" />
</body>
</html>
html at pastebin, how to call the timeout function - see for example 1, 2
if canvas would be ok you could try doing it like this ;)
var context = document.getElementsByTagName('canvas')[0].getContext('2d');
var hue = 0;
function bgcolor() {
hue = hue + Math.random() * 3 ;
context.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
}
setInterval(bgcolor, 20 );
Yes ;) it`s not perfect and just an excample but give it a try. Here is the complete pen on codepen.
One way might be to use setTimeout to call some function which incrementally changes the colour (I'm assuming background-color) by some small amount each time it's called. At each iteration, just check to see if you've arrived at your target colour and if not, increase or decrease your RGB value as necessary.
How do I get the background color code of an element?
console.log($(".div").css("background-color"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="div" style="background-color: #f5b405"></div>
What I want
#f5b405
Check example link below and click on the div to get the color value in hex.
var color = '';
$('div').click(function() {
var x = $(this).css('backgroundColor');
hexc(x);
console.log(color);
})
function hexc(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='div' style='background-color: #f5b405'>Click me!</div>
Check working example at http://jsfiddle.net/DCaQb/
There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:
var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;
function getBackgroundColor($dom) {
var bgColor = "";
while ($dom[0].tagName.toLowerCase() != "html") {
bgColor = $dom.css("background-color");
if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
break;
}
$dom = $dom.parent();
}
return bgColor;
}
working properly under Chrome and Firefox
You have the color you just need to convert it into the format you want.
Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/
In fact, if there is no definition of background-color under some element, Chrome will output its background-color as rgba(0, 0, 0, 0), while Firefox outputs is transparent.
My beautiful non-standard solution
HTML
<div style="background-color:#f5b405"></div>
jQuery
$(this).attr("style").replace("background-color:", "");
Result
#f5b405
Adding on #Newred solution.
If your style has more than just the background-color you can use this:
$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]
This Solution utilizes part of what #Newred and #Radu Diță said. But will work in less standard cases.
$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');
The issue both of them have is that neither check for a space between background-color: and the color.
All of these will match with the above code.
background-color: #ffffff
background-color: #fffff;
background-color:#fffff;