Created
September 16, 2011 14:56
-
-
Save chrisroos/1222288 to your computer and use it in GitHub Desktop.
Playing around with fading out background colours using pure Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)