Home » Labs » Apply random background colour to div with demo  

Apply random background colour to div with demo


Filed under Labs

If you would like a create a webpage which change the background color randomly every time the page is loaded then here is a fine solution. There are multiple ways to this, in this tutorial we will use a bit of JavaScript and the below code works fine with modern browsers like Google chrome, Firefox and Opera etc.

Below you can find the code used for this example and after the post there is also option for viewing an online demo of this example. Hope you enjoy this!

CSS

 
	#wrapper{
		width:100%;
		height: 380px;
		float:left;
		margin:0;
	}
	#wrapper h2{
		margin:15%;
		color:#fff;
		text-align:center;
	}

JavaScript

 
 
		function randon_colors() { 
			var color = '#'; 
			var letters = ['f1a30b','835a2c','014fef','a20025','da0174','a4c401','aa00ff','01abaa']; //You can set colors here
			color += letters[Math.floor(Math.random() * letters.length)];
			document.getElementById('wrapper').style.background = color;
		}

HTML

 
		<!-- Random Background Color -->
		<div id="wrapper">
 
			<h2>Refresh page to see the color change.</h2>
 
		</div>
 
		<!-- /Random Background Color -->

Demo

Posts you may like: