jQuery: news rotator

In this post I'm going to show you how to create a simple news rotator with jQuery. We're going to use a JavaScript timer to repeat our fading animation between one news and the other during a time span of two seconds. First, let's take a look at our HTML structure:

<div id="news">

  <div class="news">
  
    <p>...</p>
    <img/>
  
  </div>
  
  <!--other news-->

</div>

As you can see, it's a very simple structure. Our CSS styles are also simple:

#news {
 height: 200px;
 background: #ccc;
 width: 80%;
 margin: 1em auto;
 overflow: hidden;
}

#news div.news {
 height: 100%;
 overflow: hidden;
 width: 100%;
}

#news div.news img {
 float: left;
 width: 50%;
 height: 200px;
}

#news div.news p {
  margin: 0;
  width: 40%;
  float: right;
  padding: 1em;
}

The first thing we need to do with jQuery is to hide all the news, leaving only a gray empty box:

$('div.news', '#news').hide();

Then we set up an index (that will be incremented each time our timer runs) and a limit for our timer:

var index = -1;
var limit = $('div.news', '#news').length;

Now we have to create our timer that will repeat itself each two seconds. When it reaches its limit, our index will be reset and our timer will start again its cycle:

var interval = setInterval(function() {
  
   index++;
   
   if(index == limit) {
   
     index = -1;
   
   }
   
   var news = $('div.news', '#news').eq(index);
   
   news.fadeIn(2000).siblings().hide(); 
  
  
}, 2000);

We select each news by using the eq() method together with our index value, so we'll have 0, 1, 2 and so on. Then we make sure that only the current news is visible by hiding all its siblings, plus fading it into view. Note that the animation duration must match the delay time of our timer. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: news rotator”

Leave a Reply

Note: Only a member of this blog may post a comment.