Today we'll see how to create a testimonial ticker using jQuery and setInterval to switch in and out of different texts.
It'll display one testimonial at a time before cycling through to the next testimonial. It's very light weight, fast and easy to understand.
Let's get to it!
First let's start out by declaring out HTML document.
[code language="javascript"]
<div id="container">
<div class="testimonial">
<p>Div A</p>
</div>
<div class="testimonial">
<p>Div B</p>
</div>
<div class="testimonial">
<p>Div C</p>
</div>
<div class="testimonial">
<p>Div D</p>
</div>
<div class="testimonial">
<p>Div E</p>
</div>
</div>
[/code]
Next, our CSS rules for styling the testimonials. I'm going to use something very ugly, but good for illustration purposes.
[code language="css"]
#container {
outline:1px solid green;
overflow:hidden;
margin:10px;
}
.testimonial {
outline:1px solid red;
overflow:hidden;
margin:5px;
}
.testimonial p {
display:block;
margin-left:5px;
}
[/code]
Finally, let's get to the nitty gritty of this post, the javascript.
To start, we need to hide every testimonial on the initial page load.
[code language="javascript"]
$('.testimonial').hide();
[/code]
Next, let's count how many testimonials we have in the document and remember that.
[code language="javascript"]
var testimonialCount = $('.testimonial').length;
var currentItem = 0;
[/code]
Now let's declare the function that we'll call every X seconds in order to switch out the testimonials.
[code language="javascript"]
switchDiv = function() {
if (currentItem == testimonialCount - 1) {
$('.foo').eq(testimonialCount - 1).hide();
currentItem = 0;
$('.foo').eq(0).fadeIn();
}
else {
$('.foo').eq(currentItem).hide();
currentItem = currentItem + 1;
$('.foo').eq(currentItem).fadeIn();
}
}
[/code]
Finally, we'll need to setup an interval to update and switch out these testimonials. For example, this will switch out testimonials every 2 seconds.
[code language="javascript"]
setInterval("switchDiv()", 2000);
[/code]
And that's all there is to it! It's very simple to use and looks very good. :)
You can find a working example on the JSFiddle hosted here:
http://jsfiddle.net/9s5Px/30/
No hay comentarios:
Publicar un comentario