Random Color Generator in Javascript

Below is a script for a random color generator using Javascript. An explanation of how it works is in the code comments:

<script>
    function randomColor(){
		return 	"#" +  // start with a leading hash
			Math.random() // generates random number
			.toString(16) // changes that number to base 16 as a string
			.substr(2,6); // gets 6 characters and excludes the leading "0."
	}
</script>

You could then use that function like this:

<div id="test">Some Text Here</div>
<script>
    function randomColor(){
		return 	"#" +  // start with a leading hash
			Math.random() // generates random number
			.toString(16) // changes that number to base 16 as a string
			.substr(2,6); // gets 6 characters and excludes the leading "0."
	}
	document.getElementById('test').style.background = randomColor();
</script>                                            

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>