jQuery News Ticker is used to marquee a list of text one by one. If you want a JavaScript News Ticker the linked article has the code. It is a responsive news ticker plugin using Javascript.
Now we are going to see a simple news ticker example using jQuery. In this example, we are going to achieve it using few lines of code. And, we are not using any third-party plugins.
We are having an unordered list of text in this HTML. We will iterate each list item with a jQuery loop to marquee horizontally.
Ticker box HTML is,
<div id="ticker">
<ul class="news-list">
<li>"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth" - <strong><i>William W. Purkey</i></strong></li>
<li>"Be the change that you wish to see in the world." - <strong><i>Mahatma Gandhi</i></strong></li>
<li>"There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle." - <strong><i>Albert Einstein</i></strong></li>
</ul>
</div>
With the reference of the ticker box id, we are executing jQuery ticker code.
<script>
var ticker = $("#ticker");
var t;
var li_count = 1;
var li_length = $("ul.news-list li").length;
var li = $("li").first();
var runTicker = function(trans_width) {
$(li).css({"left":+trans_width+"px"});
t = setInterval(function(){
if (parseInt($(li).css("left")) > -$(li).width()) {
$(li).css({"left":parseInt($(li).css("left")) - 1 + "px","display":"block"});
} else {
clearInterval(t);
li = $(li).next();
if(li_count == li_length){
li_count = 1;
li = $("li").first();
runTicker(trans_width);
} else if (li_count < li_length) {
li_count++;
setTimeout(function(){
runTicker(trans_width);
},500);
}
}
},5);
}
$(ticker).hover(function(){
clearInterval(t);
},
function(){
runTicker(parseInt($(li).css("left")));
});
runTicker(ticker.width());
</script>
In this code, we are invoking jQuery ticker code at a periodic interval to marquee each text horizontally. There is delay time two subsequent items.
We increment a counter for each text and reset this counter variable to 0 once the loop is completed. We can pause the ticker on mouse over and resume on mouse out.