Friday, August 30, 2013

jQuery list ticker

I needed a section on a page where different texts fade in every 3 seconds. One way to implement this was to use the Riva Slider Pro plugin, but I wanted something that is much easier to use.

The simple solution was to use the List Ticker jQuery plugin created by Alex Fish. You can find it here:
http://www.htmldrive.net/items/show/411/Super-simple-jQuery-ticker-text-slideshow.html

What you need is the plugin file, which looks like this if you don't want to look for it at all:

 /* List Ticker by Alex Fish   
 // www.alexefish.com  
 //  
 // options:  
 //  
 // effect: fade/slide  
 // speed: milliseconds  
 */  
 (function($){  
  $.fn.list_ticker = function(options){  
   var defaults = {  
    speed:4000,  
       effect:'slide'  
   };  
   var options = $.extend(defaults, options);  
   return this.each(function(){  
    var obj = $(this);  
    var list = obj.children();  
    list.not(':first').hide();  
    setInterval(function(){  
     list = obj.children();  
     list.not(':first').hide();  
     var first_li = list.eq(0)  
     var second_li = list.eq(1)  
           if(options.effect == 'slide'){  
                first_li.slideUp();  
                second_li.slideDown(function(){  
                     first_li.remove().appendTo(obj);  
                });  
           } else if(options.effect == 'fade'){  
                first_li.fadeOut(function(){  
                     second_li.fadeIn();  
                     first_li.remove().appendTo(obj);  
                });  
           }  
    }, options.speed)  
   });  
  };  
 })(jQuery);  

All you have to do is to put it in the header after jQuery like this:

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

The content that you want to fade or slide has to be put in an unordered list like this:

 <ul id="ticker">  
      <li>Lorem ipsum dolor sit amet</li>  
      <li>Consectetur adipisicing elit</li>  
      <li>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</li>  
      <li>Ut enim ad minim veniam</li>  
      <li>Duis aute irure dolor in reprehenderit in voluptate</li>  
 </ul>  

The last step is to initialize the whole thing:

 <script type="text/javascript">  
      $(document).ready(function(){  
           $('#ticker').list_ticker({  
                speed:2000,  
                effect:'fade'  
           })  
      })  
 </script>  

If you are using Wordpress and the last part doesn't seem to work, try this instead:

 <script type="text/javascript">  
      jQuery(function ($) {  
           $(document).ready(function(){  
                $('#ticker').list_ticker({  
                     speed:2000,  
                     effect:'fade'  
                })  
           })  
      });  
 </script>  

Also don't forget to style the list to make it pretty!