This blog has moved here: woorkup.com | FOLLOW ME ON TWITTER @woork
Tuesday, May 26, 2009

How to implement a news ticker with jQuery and ten lines of code

After my previous posts about how to implement a news ticker with MooTools I received a lot of emails from my readers that asked to me to implement a similar feature with jQuery, including fade in and fade out effects, in the simpler possible way. So in this post I want to illustrate you how to implement a nice news ticker using jQuery and just ten lines of Javascript code. The result is something like this:



I suggest you to take a look at this live preview and download the source code to understand how it works. In the source code I added a file called base.html that contains the basic structure of this ticker you can quickly reuse and customize in your web project.





A little introduction
Step 1: image to have a <ul> list with ID = listticker. This list contains some list elements <li> (in this case: My News 1, My News 2, ...). First step is: get the first element of the list, save its content into a var and remove it using a fade out effect.



You can get the HTML code contained into the first element of the list (#listticker) and assign it to a var (first) using this simple code:

first = $('ul#listticker li:first').html();


To use fade out effect and remove the element you can use this code:

.fadeOut('slow', function() {$(this).remove();});


Step 2: now you have to add the content saved into the var first to the end of the list:


You can use this simple code:

$('ul#listticker').append(first)


...where first is the var you used to save the content of the first element in the step 1.

Step 3: Now you have to move up the content of the list (My News 2 is now the first element of the list) and repeat the entire process from the step 1.




In Javascript code section of this tutorial I used setInterval() to repeat the process every 3 seconds (3.000 milliseconds). Ok, now take a look at HTML and Javascript code.


HTML Code
HTML code is really simple. The only thing you have to do is adding an <ul> list with ID = listticker and some list elements:

<ul id="listticker">
<li>My News 1</li>
<li>My News 2</li>
<li>My News 3</li>
<li>My News 4</li>
<li>My News 5</li>
</ul>

Remeber to add into the tag <head> of the page where you want to implement this ticker a link to jQuery:

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


Javascript Code
Take a look at the follow code. I implement 2 functions removeFirst() and addLast(). Each function contains five lines of code. Total lines for "conceptual" code: 10 lines! I promised! :)

<script type="text/javascript">
$(document).ready(function(){

var first = 0;
var speed = 700;
var pause = 3000;

function removeFirst(){
first = $('ul#listticker li:first').html();
$('ul#listticker li:first')
.animate({opacity: 0}, speed)
.fadeOut('slow', function() {$(this).remove();});
addLast(first);
}
function addLast(first){
last = '
  • '+

  • first+'';
    $('ul#listticker').append(last)
    $('ul#listticker li:last')
    .animate({opacity: 1}, speed)
    .fadeIn('slow')
    }

    interval = setInterval(removeFirst, pause);
    });</script>


    In the last line I used:

    interval = setInterval(removeFirst, pause);


    ...it calls the function removeFirst()every 3 seconds (3000 milliseconds) and in this way I create ad infinite loop.




    If you have suggestions to improve the code please leave a comment. Thanks!


     
    News ticker with horizontal scrolling
    Fantastic News Ticker Newsvine-like
    Automatic news ticker with vertical scrolling and Start/Resume optionsJoomla! extension: super news ticker

    blog comments powered by Disqus
    e okul said...

    Very good..thanks

    Rahil Pirani said...

    Very Nice! Will be a great tool to add to my site!

    Christoph said...

    You don't have to use animate() AND fadeIn/Out().

    Simply use fadeOut(speed, callback) or fire the callback function from animate()

    coda said...

    You're fading in the last element of the list which is out of view. Check your demo to see what I mean. Depending on how many list items exist in total and how many you want to be visible at one time, you'll need to determine the correct list item on which to apply the fade.

    Also it would be more flexible to determine the height of the list items and subsequently the height of the visible area dynamically instead of using a fixed px height. And a setting to control how many list items are visible at one time would be useful too.

    Thanks for the script - very useful technique! I never thought about it like that before.

    sofian hanafi said...

    please also share the back-end apps. for news ticker.

    3faycom said...

    very nice work.Surely I will try it in my future projects...

    ny web design said...

    Very Nice! Will be a great tool to add to my site!

    Raf said...

    I think it would be nicer if all the elements were sliding up (while the first one is fading out). That would make the whole process smoother.

    Srinivas Tamada said...

    Great Article..

    Webmonkey-in-Ireland said...

    Thanks for posting Antonio. Really useful for the bookmarks.

    Soh Tanaka said...

    Very cool. I always wondered how that was achieved. Thank you very much~

    srini said...

    Simple,cool stuff..showing the power of jQuery

    HieuUK said...

    Really good examples, special with a few lines of code. It would be nicer if you make the animation to move the stack up instead of leave it like that.

    Otto said...

    It would be useful to make it stop while hovering the mouse at it :)

    Nice post anyway.

    Aliester said...

    Nice work,You give full information regarding jQuery and ten lines of code,It is very useful to me.
    Thanks!

    jesgo said...

    Really good work.
    Thanks.

    FreewareMatter said...

    This is a very basic effect of jQuery. Nothing specially. But thank you.

    Donna said...

    Thanks. This is new to me and your code allowed me to follow easily. However, I want to customize it with new images and text. The text works out fine, but I cannot view the images I wish to use (empty "frame" appears in place where image should be). I converted .jpg to .png using Paint. I made sure each image size matched yours. Any advice? Thanks! Donna

    Pedro Magalhães said...

    Well Done!

    Zoli said...

    Very good tutorial. It's easy to follow. Just starting to code this now. Thanx.

    Edwinpaendong said...

    Syallom..!

    Hm... very nice.
    Thanks

    Abdel Olakara said...

    Superb! This is a great tutorial and I will bookmark it! Thanks :-)

    Voigtan said...

    I did some changes, liked the idea you done man Im following your blog and love the articles you write. Here are some cleanup code (I dont delete any of the elements):

    $(document).ready(function(){
    var speed = 700;
    var pause = 3500;
    function removeFirst(){
    $('ul#listticker li:first').fadeOut('slow', function() {addLast(this);});
    }
    function addLast(first){
    $(first).insertAfter('ul#listticker li:last').fadeIn('slow');
    }
    interval = setInterval(removeFirst, pause);
    });

    Zoom said...

    thanks antonio, i want to try it..

    Varun said...

    This is a nice tutorial, but there are some things that could be improved. For one in your example you have set the height manually, but this could be improvedd by dynamically calculating the height using jquery. The code for that would be

    $(window).load(function() {
    $('ul#news-ticker').height($('ul#news-ticker').height()).css({overflow:'hidden'});
    });

    Also the fading in of the last element is unnecessary as it is hidden when you are fading it it.

    I based the jQuery code I wrote for my own tutorial at pointsontheline.com on this, although I made rather heavy changes to make it conform to exactly what I needed.

    Thanks once again.

    Varun said...

    Oh by the way, I forgot to mention that christoph is right when he says you dont have to use animate() and fadeIn()/fadeOut()

    Csaba said...

    Your tutorials are amazing Antonio. I really like them.

    thatDuDE said...

    cool stuff there..gonna use it in my site!

    web design st louis said...

    great post. Gonnna be an awesome tool.

    Robin said...

    Ahh, jQuery - is there nothing it can't do? :) Great tutorial, learned a few things!

    Anonymous said...

    Hi can anyone help please? New to coding and I am having trouble using a jquery code in html. The code can be found here http://www.unwrongest.com/projects/airport/
    Im trying to use it on my site but need it in html. Any help offered would be truly appreciated. Many Thanks.

    India Web said...

    Hey first of all thanks for such great & nice tool.It is helpful to me lot for my new website.

    paul said...

    very nicely done! i like the referencing links you provided also! really good..

    just out of curiosity, how long have you been doing j query and php for?

    • Twitter Follow woork on Twitter
    • RSS Feed Subscribe to stay up to date
    • Podcast Coming soon...
    • 0 delicious lovers save
    Share your links. Do you want to suggest any interesting link about web design or tech news? Submit your link.
    Submit a News