Random Background Color with Javascript

random background color with javascript
It’s been a long while since I started studying coding again, though I did learn more while working on an Inventory System CMS for Appliances Connection. This time around it’s no longer just about PHP. I added a new subject to my self-study curriculum — Javascript. Thanks to YouTuber mmtuts, he made learning Javascript a breeze.

So for the first project for Javascript, I am making a page with a background color that changes from one random color to another every 1 sec. How did we do this? By using Javascript to manipulate the page’s body’s background color style via its id.

javascript code

I gotta admit, I wasn’t able to do it without Anis Sarker’s Video Tutorial. However, although I copy most part of his code, it is imperative that we, at least, understand it, otherwise, it would be just copy and pasting and nothing more.

By analyzing his code, I was able to understand what he did, and how his codes made it possible. Here, I am going to break it down and explain each functions. I am also going to make it as brief and easy to understand as much as I could. OK, let’s go…

This is the complete code and this is how it looks like when opened:

<!DOCTYPE html>
<html>
<head>
<title>Changing Background Color</title>
</head>
<style>
	body{
		width: 60%;
		background: #ffff00;
		margin: 40px auto;
		font-family:'Open Sans', sans-serif;
		/* transition fade in effect */
		transition: 4s;
	}

</style>
<body class="randombackgroundcolor" id="randombackgroundcolor">
<h1>Changing Background Color with Javascript</h1><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ut neque magna. Vivamus sed tempus neque, at tempor velit. Donec efficitur ligula eget nisl semper, quis eleifend urna dapibus. Sed congue leo ut ligula pharetra posuere. Integer ultrices nibh non semper facilisis. Fusce ut nibh molestie, tincidunt turpis at, molestie tortor. Sed semper tellus nec nisl convallis condimentum. Etiam aliquam eget odio et dictum. Nam tempus leo et aliquam lobortis. Nulla dictum ex ut tellus mattis pharetra et eu velit. Morbi et elit tincidunt, pellentesque lorem suscipit, feugiat nisi.<br><br>

Nulla facilisi. Nulla molestie, neque ac pellentesque imperdiet, ex sem ultrices ipsum, et mollis neque dui at mauris. Nulla facilisi. Sed maximus euismod iaculis. Ut vulputate sodales nunc a elementum. Vivamus vestibulum eleifend nulla vitae tempus. Duis vitae est orci. Nam pretium lectus sit amet finibus tempus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam erat volutpat. Pellentesque augue elit, gravida vel maximus vel, hendrerit ut libero.<br><br>

Nulla ultricies, risus vel accumsan fermentum, diam ante porta lectus, vitae tristique elit turpis eu arcu. Sed fringilla et justo ut porta. Donec et consequat elit. Morbi pharetra quis velit id congue. Nunc ornare mauris ante, non porttitor lectus vestibulum in. Aliquam vestibulum libero sed nisi luctus luctus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Integer ultricies libero sit amet mi tincidunt varius. Nunc tristique elementum elit sed cursus. Quisque porttitor venenatis ante, eu lobortis metus tincidunt in. Donec et ultricies massa. Nullam dapibus sed tellus eget luctus. Duis non ornare dui. Sed vitae lacus et libero mattis vulputate quis id eros.<br><br>

Aenean non felis sapien. Donec auctor vel lectus nec consectetur. Nunc consequat blandit nulla eu ullamcorper. Vivamus luctus tortor mi. Nullam quis neque eu nulla tempor malesuada ut sit amet ligula. Phasellus aliquet gravida accumsan. Phasellus auctor mollis arcu. Nulla maximus felis at lobortis commodo. Nam mattis, turpis a viverra facilisis, lorem nibh interdum tellus, sed congue tellus nibh id orci.<br><br>

Sed pretium ornare facilisis. Integer vulputate mattis velit sit amet maximus. Aenean semper diam eget massa dapibus pharetra. Pellentesque lacinia, massa quis fermentum interdum, massa sem molestie augue, ut lacinia nisl odio non eros. Ut eleifend, magna eu varius sodales, metus dolor ullamcorper enim, vitae scelerisque sapien dui et est. Fusce mollis lorem a vestibulum luctus. Duis eu enim non dui commodo fermentum. Vestibulum molestie purus et cursus viverra. Integer ut tortor vel nibh facilisis auctor vitae non lacus.<br><br>
</body>
<script type="application/javascript">
	// enclosing function in () means immediate execution of code
	setInterval(function(){
		// corresponds to rgb
		// Math.round rounds off, Math.random picks random number
		var red = Math.round(Math.random() * 255); // Red color
		var green = Math.round(Math.random() * 255); // Green color
		var blue = Math.round(Math.random() * 255); // Blue color

		// rgba("red","green","blue")
		var bg = "background: rgba(" + red + "," + green + "," + blue + ");";
		// targetting id randombackgroundcolor which is the id for the body
		var element = document.getElementById("randombackgroundcolor");
		// tells the browser to use var bg as style for var element
		element.style = bg;
	// interval 1000 milliseconds or 1 sec
	}, 1000);
</script>
</html>

I think I might have to skip the HTML and Style part of the page and go directly to Javascript, though, I would like to point this style:

body{
        transition: 4s;
    }

Transition gives the transition effect, wherein the applied effect would be gradual instead of instantaneous. For this page, we are setting transition to 4s. Meaning the change from one effect to another takes 4 seconds to complete the entire transition cycle. Let’s say, the background color changes from Red to Yellow. Before the page completely turns to Yellow, it takes, at least, 4 seconds. Because of this, the change from Red to Yellow will have to undergo some gradual transitional changes, wherein it would display several other colors found in-between Red and Yellow as the color shifts from Red to the Yellow spectrum.

Example:

Now, for the Javascript part, notice the function setInterval? setInterval is a Javascript function that controls the interval between firing each command or function. In this case, we are encapsulating a Javascript function in (). Then, at the end of setInterval parenthesis, the time (in milliseconds) has to be set. In this case 1000, which is equivalent to 1 second. Which means, every 1 sec, the script will fire.

setInterval(function(){
	Javascript code here...
}, 1000);

Next, we define the variables for the colors corresponding to RGB (Red, Green, Blue). In the code below, we assign a random number, ranging from 0-255 using the Math.random function. The function will throw a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range, which is then multiplied with 255 and rounded off using Math.round. During this event, a random float let’s say 0.5, will be generated. It will be multiplied to 255 and give us 127.5 then it will be rounded off to the nearest integer giving us 128. 128 will be the value of that variable, thus giving us random rgb colors.

	var red = Math.round(Math.random() * 255);
	var green = Math.round(Math.random() * 255);
	var blue = Math.round(Math.random() * 255);

Next is to create a variable that will convert the code to string for the style. Notice that the code is encapsulated in-between two “. It means this variable will be a string. The + sign is a string operator that concatenates (combine) the other values. In the code below, we have the string background: rgba(” merged with var red merged with a comma string, merged with var green, followed by a comma, and var blue, and finally “);. At the end, we get a string “background: rgba(“0″,”1″,”2”); where 0, 1, 2 corresponding to a random value between (0-255).

	var bg = "background: rgba(" + red + "," + green + "," + blue + ");";

The next variable below (var element) contains the Javascript function document.getElementById that targets a specific id used by HTML tags or elements. In this case, we are targeting the id “randombackgroundcolor” which is used by the tag (see complete code above).

	var element = document.getElementById("randombackgroundcolor");

Finally, we have the element.style, which is calling the method style. Note that “element” is actually the variable containing the Javascript code document.getElementById(“randombackgroundcolor”);. Attaching style to the variable with “.” will apply that method to the variable. In the code below, it means that it will get var bg that contains the background color style to be use as the style for the tag using the id=”randombackgroundcolor”, thus swapping the body’s background color to randomly-generated colors.

	element.style = bg;

So that’s it! That’s how it’s done. Well, not that I’m boasting or anything but I get to understand it just by skimming through the code. That maybe because I had previous coding experience with PHP, and Javascript isn’t that much of a difference, though it is important to understand the Javascript basics first, which I have using this tutorial.

Follow me at:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.