Tuesday, April 19, 2011

single line news/feed scroller with jQuery

How Do I? Single Line news/feed Scroller with jQuery

Working Preview:

  • scroll headline 1
  • scroll headline 2
  • scroll headline 3
  • scroll headline 4
  • scroll headline 5

While working on my own, I decided to implement a very simple news/feed one line scroller. Idea is simple and in use a lot of websites. Doing it with jQuery is a pleasure.

It will use the Unordered List and will scroll each List Item according to predefined scroll interval. Also while this scrolling is going on, each item will do it with Scroll animation of jQuery.

It is a recursive function and it will schedule call with itself again and again to continue scrolling. It has no stopping criteria as associated with must do recursive functions as it required to be scrolled all the time.

Parameters Detail
It takes 4 parameters.
Unordered List Id: ulId
If you call it firstTime then this bit will be true : isFirstTime
Time between next news/feed: scrollTimeInterval
Time of animation when changing news/feed: animationTimeInterval

Please see the code as listed below and download link is at the end of this article.

//call the function when document is ready to start the scrolling
$(function(){
    ScrollMessages("ulHeadlines",true,3000,1000);
});

function ScrollMessages(ulId,isFirstTime,scrollTimeInterval,animationTimeInterval) 
{
    //Get the Unordered List
    var ul=$("#"+ulId);
    //Get all List Items
    var lis=$("li", ul);
    //If it is not the first time, Current item is the visible one
    var current = $("li:visible:first", ul);
    //if it is the first time, it is the first item of list. Show the first item of list 
    if(isFirstTime)
    {
        //hide all list items
        lis.hide();  
        //get the first list item
        current=$("li:first",ul);
        //show only the first item
        current.show();
    }
    //if it is not the first time then calculate the next item to show and show that item.
    else
    {
        //Get the index of item that will be shown 
        var index=current.index();
        //if it is the last item then current items should be the first item of list else it should be the next item of list
        if (index + 1 == lis.size()) {
            index = 0;
        }
        else {
           index += 1;
        }
        //slide up and hide the current item
        current.slideUp(animationTimeInterval);
        //slide down the next item that is going to be shown 
        $("li:eq(" + index + ")", ul).slideDown(animationTimeInterval);
    }
    //re call this funcation to continue the scroll news recursively
    setTimeout(function(){ScrollMessages(ulId,false,scrollTimeInterval,animationTimeInterval);}, scrollTimeInterval);
}

Click here to download sample

1 comment:

  1. Your perspective on this topic is truly refreshing. I appreciate the unique angle you've taken

    ReplyDelete