written on:31 Aug, 2009 by Alen Grakalic

Simple Way to Random Display or Rotate Content Using JavaScript and CSS

Delicious Digg StumbleUpon Reddit Subscribe to RSS Feed

In a project I did recently there was a need for randomly displayed content in form of one of those "Did you know" tips. There were 8 to 10 paragraphs of text and client wanted to display just one randomly chosen. Since that was the static site I decided to go with front end solution. I am aware that there are many more elegant back-end solutions but read on and you'll see that there are advantages to this as well.

Download the script files

Take a look at the randomly displayed content demo

Take a look at randomly rotating content demo

Let's Get Started

So first the markup. I placed all of the "did you know" tips into one unordered list:

<ul id="tips">
	<li>... if you want to become a better coder you need to eat your vegetables?</li>
	<li>... it takes more time to code a web page then to make a pizza?</li>
	<li>... you should validate your code?</li>
	<li>... jQuery is your friend? For real!</li>
	<li>... no matter what some people claim, you can't learn CSS in 3 hours?</li>
</ul>

The idea is to HIDE all of the tips and then display randomly chosen one using JavaScript.

So to style and hide the tips we use the following CSS code:

#tips, #tips li{
	margin:0;
	padding:0;
	list-style:none;
	}
#tips{
	width:250px;
	font-size:16px;
	line-height:120%;
	}
#tips li{
	padding:20px;
	background:#e1e1e1;
	display:none; /* hide the items at first only */
	}

The downside to this solution is that initially all of the tips are hidden, so users with disabled JavaScript and enabled CSS will not be able to see them at all while users with disabled JS/CSS (as well as search engines) will see all of them.

To display one of them randomly we will use small jQuery script. Of course you will have to download jQuery put it somewhere on your server and link to it by placing this code inside the head tag of your document (link to your jQuery.js file).

<script type="text/javascript" src="js/jquery.js"></script>

Below that add the following script:

<script type="text/javascript">

this.randomtip = function(){
	var length = $("#tips li").length;
	var ran = Math.floor(Math.random()*length) + 1;
	$("#tips li:nth-child(" + ran + ")").show();
};

$(document).ready(function(){	
	randomtip();
});

</script>

Short one isn't it. Take a look at the demo (refresh the page couple of times) to see how it works.

Taking it One Step Further

If this simple functionality doesn't satisfy you, here's more. With modifying the above code a bit we can get fade in/out tips that rotate randomly. Of course the code doesn't allow same tip to display twice in a row.
Note that you are able to modify length of the pause between random rotations.

<script type="text/javascript">

this.randomtip = function(){

	var pause = 3000; // define the pause for each tip (in milliseconds) 
	var length = $("#tips li").length; 
	var temp = -1;		

	this.getRan = function(){
		// get the random number
		var ran = Math.floor(Math.random()*length) + 1;
		return ran;
	};
	this.show = function(){
		var ran = getRan();
		// to avoid repeating
		while (ran == temp){
			ran = getRan();
		}; 
		temp = ran;
		$("#tips li").hide();	
		$("#tips li:nth-child(" + ran + ")").fadeIn("fast");		
	};
	
	show(); setInterval(show,pause);
	
};

$(document).ready(function(){	
	randomtip();
});

</script>

Take a look at this demo to see it in action.

Thanks for reading this! If you liked the script please remember to bookmark it, share it and subscribe to rss feed using the links below :) Cheers!

About the author:

cssglobe's image Designer, developer and a passionate standardista with huge experience in all types of front-end work. I've been featured on numerous css galleries including famous Css Zen Garden official list. Drop me a line if you have work proposition or if you'd simply like to say hello.
To stay in touch, follow me on Twitter.

Enjoyed the article?

Then don't miss our next one! Subscribe to our RSS feed or share it with your friends.

Delicious Digg StumbleUpon Reddit Subscribe to RSS Feed

Read more! Here are our most recent articles:

View All Articles

Comments

  • Jasmin Halkić on 31 Aug, 2009 wrote:

    Awesome... Nice and useful article.
  • Veerendra on 31 Aug, 2009 wrote:

    wow .. wonderful article, I was thinking about that kind of stuff .. is it possible to access this code through Wordpress ?
    thanks for sharing !!!
  • Pieter on 31 Aug, 2009 wrote:

    About the automatic rotating content, there's always a flash of white background when it rotates.
    It's easily fixed:
    apply background:#e1e1e1; to #tips too. That should fix it, the background doesn't flash anymore!

    And about the accessibility issue:
    Remove display: none; from the CSS and modify the Javascript to this:
    $(document).ready(function(){
    $("#tips li").hide();
    randomtip();
    });
    And tataa, every user sees the list:
    CSS, no JS;
    No CSS, JS;
    Both;
    None.

    Nice script ;)

  • cssglobe on 31 Aug, 2009 wrote:

    @Pieter: if you use $("#tips li").hide(); in JS you will have all of the tips displayed before page loads and then when the page-load is done the script will hide all tips and show one. I wanted to avoid that to be honest.
  • Dalesh Kowlesar on 31 Aug, 2009 wrote:

    This can be very useful. Thanks!
  • cancel bubble on 31 Aug, 2009 wrote:

    I'm curious, why are you doing:

    this.randomtip = function(){

    In particular, why are you using "this" and not var - or better yet, wrapping it up in a singleton/module pattern?
  • cssglobe on 31 Aug, 2009 wrote:

    @cancel bubble: a habit, nothing else.
  • Enrico Lamperti on 31 Aug, 2009 wrote:

    Nice and simple!
  • Rahul - Web Guru on 31 Aug, 2009 wrote:

    Quite nice and tidy... thanks.
  • Diego on 31 Aug, 2009 wrote:

    Ellegant and simple,
    Thanks!
  • Vicky Rowe on 2 Sep, 2009 wrote:

    Cool code, works as it should!! After a couple hours of playing with code, this is a great find.
    I set the width in the CSS, and it is displaying wide. Ideas on how to get the width to adhere to 215? Currently it seems to be showing at about 400px wide......
    page is at http://www.satoridigitalmarketing.com/clients/traverslasik/template.html

    Vicky
  • cssglobe on 2 Sep, 2009 wrote:

    @Vicky: the css for this script is pretty basic and straightforward. What you should look out for is inherited css as well as extra elements (I noticed an empty <p> in your source code).
  • Vicky Rowe on 2 Sep, 2009 wrote:

    Thanks. I'll dig it out. The CSS for this durn site (I'm doing a re-write from someone elses code) is a labyrinth, spread across several files. I need a ball of string to leave myself a path to find my way back out, LOL.
  • Randy Verbeck on 2 Sep, 2009 wrote:

    @cssglobe: I've adopted your script into a client's website. The tips are near the bottom of the page. However when you scroll to very bottom, it jumps up a bit when the tip changes. I'll scroll down again, and it jumps up with the next tip. Any ideas?
  • Randy Verbeck on 2 Sep, 2009 wrote:

    Nevermind on that. Wrapped it in a div and problem solved.
  • M Patel on 5 Sep, 2009 wrote:

    Simply superb post. I have enjoyed this post along with other popular articles such as "Wordpress Find Pages Top Level Parent ID". I have marked your blog as one of the Top 100 Nice blogs - see it here: http://kpobuddy.wordpress.com/2009/07/22/top-class-100-blogs-for-website-designers-and-web-developers/
  • Susan on 9 Sep, 2009 wrote:


    I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.

    Susan

    http://dclottery.info

  • Helio Pascoal on 16 Sep, 2009 wrote:

    I liked it a lot. I'm designing our church's website and I came accross a little problem. I've tried to use both scripts in the page, one for a rotating news and the other for a random bible verse. But they don't work together. Would you help me with that? Thanks
  • Schop on 24 Sep, 2009 wrote:

    I like this! Simple solution to something a lot of people want on their blogs or webapges....
  • Brian on 30 Sep, 2009 wrote:

    Using the random version on Safari 4.0.3, I noticed that sometimes the the div disappears on a refresh

Sorry, further comments are disabled for this post.

Hey, you are not logged in!
Apply for a membership or login here.

Subscribe to CSSG Feed

Want to join?

If you wish to contribute with your own articles, updates or gallery entries you can apply for a membership and even become our editor.

Apply here

Become a friend