Skip to content

Instantly share code, notes, and snippets.

@santosh
Created January 7, 2013 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santosh/4472207 to your computer and use it in GitHub Desktop.
Save santosh/4472207 to your computer and use it in GitHub Desktop.
JavaScript: Changes CSS value on a regular interval of time. This example will show how to change background color of body every 1 second
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Random Color Generator in JavaScript </title>
<script type="text/javascript" charset="utf-8">
// generate random color
function colorname() {
return '#' + Math.floor(Math.random() * 0xFFFFFF << 0).toString(16);
}
// get rid of window.onload stuff by putting entire script in the body
window.onload = function() {
var everyOneSecond = function() {
// See https://developer.mozilla.org/en-US/docs/DOM for reference of DOM.
document.body.style.backgroundColor = colorname();
};
// time in milliseconds
setInterval(everyOneSecond, 1000)
};
</script>
</head>
<body>
</body>
</html>
@santosh
Copy link
Author

santosh commented Jan 7, 2013

Another way to generate random colors:

var hex = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
var ranval = function() {
    return hex[Math.floor(Math.random()*hex.length)];
}
var colorname = function() {
    return "#" + ranval() +ranval() + ranval() + ranval() + ranval() + ranval();
}

// call the colorname();

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