Skip to content

Instantly share code, notes, and snippets.

@chrisroos
Created September 16, 2011 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisroos/1222288 to your computer and use it in GitHub Desktop.
Save chrisroos/1222288 to your computer and use it in GitHub Desktop.
Playing around with fading out background colours using pure Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Background colour fadeout test</title>
</head>
<body>
<h1>Background colour fadeout test</h1>
<p>I wanted to work out how to fade background colours using pure Javascript.</p>
<script src="fadeout.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
function RGB(cssColor) {
if (/rgb\(/.test(cssColor)) {
var m = cssColor.match(/rgb\((\d+), (\d+), (\d+)\)/);
this.opacity = 1;
} else if (/rgba\(/.test(cssColor)) {
var m = cssColor.match(/rgba\((\d+), (\d+), (\d+), (\d+(\.\d+)?)\)/);
this.opacity = m[4];
}
this.red = m[1];
this.green = m[2];
this.blue = m[3];
}
RGB.prototype.toString = function() {
var rgba = [this.red, this.green, this.blue, this.opacity].join(', ');
return 'rgba(' + rgba + ')';
}
RGB.prototype.fade = function() {
this.opacity = this.opacity - 0.1;
return null;
}
function fadeBackground(element) {
this.fade = function() {
var rgb = new RGB(element.style.backgroundColor);
if (rgb.opacity == 0) {
clearInterval(this.timer);
} else {
rgb.fade();
element.style.backgroundColor = rgb.toString();
}
}
this.timer = setInterval(this.fade, 100);
}
var div = document.createElement('div');
div.appendChild(document.createTextNode('hello world'));
div.style.backgroundColor = '#ff0';
document.body.insertBefore(div, document.body.children[0]);
fadeBackground(div);
Copy link

ghost commented Apr 15, 2021

Hey, this is an excellent code! It helped me a lot but I was wondering if you could make it work for safari on mobile please with siri shortcuts. It would be awesome! You would be the first to produce a working code to fade the background on mobile :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment