Display Random Content with JavaScript

Posted on January 6, 2012 by Dan Doicaru in jQuery/JavaScript Category

In this tutorial we'll learn how to create a simple script in JavaScript that will randomly change your desired news or content when you will load the page.

Display Random Content with JavaScript

Files Needed

We'll need to create 2 files. See the image below:

HTML Structure

Now open "index.html" with any text editor and write the basic html.

Note: You can double click the text to Select All and Copy.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>How to Display Random News or Content with JavaScript</title>
	<script language="javascript" type="text/javascript" src="javascript.js"></script>
</head>

<body>

	<div id="news1">
		This is the 1st news box with a <a href="http://m.html-tuts.com">link</a> inside.
	</div>

	<div id="news2">
		This is the 2nd news box and you can basically write everything inside those &lt;divs&gt;.
	</div>

	<div id="news3">
		This is the 3rd news box with a <b>bold text inside it</b>.
	</div>

	<div id="news4">
		<p>
			This is the 4th news box with <i>italic text inside it</i> and unordered list:
		</p>

		<ul>
			<li>Example1</li>
			<li>Example2</li>
			<li>Example3</li>
		</ul>
	</div>

</body>
</html>

After we wrote all these rows without any CSS Styles or JavaScript applied to our tags, your HTML document will show all content at once.

Display Random Content with Javascript

So to make the things work, open "javascript.js" with any text editor and you'll need to create:

  • A variable called "randomNumber" that will generate the random number.
  • 2 functions inside our variable: "Math.floor" and "Math.random".
  • A function that will hide the other news when the page will load.
randomNumber = Math.floor(Math.random()*4+1);

window.onload = function() {
	if (randomNumber == 1) {
		document.getElementById("news1").style.display = "inline";
		document.getElementById("news2").style.display = "none";
		document.getElementById("news3").style.display = "none";
		document.getElementById("news4").style.display = "none";
	}
	if (randomNumber == 2) {
		document.getElementById("news1").style.display = "none";
		document.getElementById("news2").style.display = "inline";
		document.getElementById("news3").style.display = "none";
		document.getElementById("news4").style.display = "none";
	}
	if (randomNumber == 3) {
		document.getElementById("news1").style.display = "none";
		document.getElementById("news2").style.display = "none";
		document.getElementById("news3").style.display = "inline";
		document.getElementById("news4").style.display = "none";
	}
	if (randomNumber == 4) {
		document.getElementById("news1").style.display = "none";
		document.getElementById("news2").style.display = "none";
		document.getElementById("news3").style.display = "none";
		document.getElementById("news4").style.display = "inline";
	}
}

Understanding the Code

In this step we will explain the JavaScript code:

randomNumber -  is a variable and you can change his name as long as you type it correctly everywhere in the script.

Math.floor(number) - returns the integer of a number. For example:

  • Math.floor(0.2) returns 0
  • Math.floor(-6.1) returns 7

Math.random() - returns a number between 0 and 1. In our case Math.random()*4 returns a number between 0 and 3, and we need between 1 and 4 so you will add +1 at the end. For example:

  • Math.random() returns 0.42362819185
  • Math.random()*4+1 returns a number between 1 and 4
  • Math.random()*10 returns a number between 0 and 9
  • Math.random()*5+2 returns a number between 2 and 6
window.onload = function() {
    // code
}

This will create a function, and when the page is being loaded all that code inside the function will run only once. If you refresh the page the code will run again, and so on.

document.getElementById("news1").style.display = "inline";

This function will get the element from your HTML document with the ID specified (in our case 'news1') and will set the CSS Style Property to "inline" or "none"

Download Files

Live Demo

Related Articles
Comments
  1. Aistis says:

    Awesome, thank you mate ! :)

  2. Jerry says:

    Thanks for publishing. This is great and simple to implement. One question: I am briefly seeing all of my html (for everything in all of the div tags) flash briefly, before just the random div displays. I have added longer html including images in each div so I have more code than the example. Any suggestions to get around this?

    Thanks!

  3. Dave says:

    Hi there… I totally love this script and would love to use it. I just have one question if you don’t mind?
    Using your example of news stories… Is it possible to to have more than one random news story displaying?
    I’m working on a new design (LONG overdue) for my personal website http://www.davidatkinson.com and I want to display some jokes on various pages, and it would be cool if I could display multiple random jokes, maybe four or five or something on each page.
    Regards :)

    • You can include your jokes inside the divs, for example:

      <div id="news1">
          <p>Joke 1</p>
          <p>Joke 2</p>
          <p>Joke 3</p>
          <p>Joke 4</p>
      </div>
      

      Then again repeat with another div (“news2”) and include another 4 jokes. When you will refresh the page it will display randomly another div with another set of jokes. Hope it helps.

    • Dave says:

      Yeah I realised that. But I would have likes to display totally random selections as opposed to groups :)

      • Be more specific please. If you want to place Facebook Likes to every group of jokes, you need to hack the facebook code a little. Not sure if this is what you want.

        • Dave says:

          I just want to display four (for example) different jokes on EVERY load, not a group of four jokes. Otherwise those same groups of four jokes will display.

          Currently, the groups will always contain the same four jokes in each group. Just the group would be random as follows:

          Group 1
          Joke 1
          Joke 2
          Joke 3
          Joke 4

          Group 2
          Joke 5
          Joke 6
          Joke 7
          Joke 8

          I would like to be able to do as follows:

          Joke 2
          Joke 5
          Joke 8
          Joke 1

          Then the next time the page is loaded, another completely random set of jokes.

          Does that make sense?
          It may not even be possible with this script, that’s why I am only asking.
          Thanks.

  4. Renz says:

    Thanks it works great!

Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.


+ 9 = 11

Search
Subscribe by E-mail

HTML-TUTS is created and maintained by Dan Doicaru.
This website is a rebrand to Extreme Design Studio (extremestudio.ro), built under WordPress platform.