Scroll Up Headline Reader

read 112 comments

A couple weeks ago someone on the jQuery discussion list asked if someone could reproduce a rotating headline box in which the headlines, in succession, scroll up into the box, pause, and then scroll up out of the box. Since I already had some code for rotating images on a page, I decided to recycle it and take the challenge.

Here is the finished product. (Please note that if you are looking at this in a feed reader, you won't be able to see the effect. )

Get Started with the HTML and CSS

The first thing I did was throw a simple page together using a single container DIV with an id of "scrollup" and four or five DIVs with a class of "headline" to hold each headline.

HTML:
  1. <div id="scrollup">
  2.   <div class="headline"> ... </div>  
  3.   <div class="headline"> ... </div>  
  4.   <div class="headline"> ... </div>  
  5.   <div class="headline"> ... </div>    
  6. </div>

I then added this simple CSS to the scrollup ID and the headline class:

CSS:
  1. #scrollup {
  2.   position: relative;
  3.   overflow: hidden;
  4.   border: 1px solid #000;
  5.   height: 200px;
  6.   width: 200px
  7. }
  8. .headline {
  9.   position: absolute;
  10.   top: 210px;
  11.   left: 5px;
  12.   height: 195px;
  13.   width:190px;
  14. }

That made all of the headlines absolutely positioned in relation to their containing box, which got a height and width of 200px. Notice that the top of all of those headlines is 210px, and the overflow property of the container is set to hidden, so none of the headlines would be showing — until they were ready.

Set Up the jQuery

At the top of the jQuery file I defined variables for the total number of headlines, the interval between headlines, the current headline, and the "old" headline:

JavaScript:
  1. var headline_count;
  2. var headline_interval;
  3. var current_headline = 0;
  4. var old_headline = 0;

Then I set the headline_count variable to be the number of div elements that have a class of "headline." But that number can't be computed until the DOM is loaded, so I wrapped the variable in jQuery's $(document).ready() function. I also wanted to set the first headline's "top" property so that it would be immediately visible, while the others would remain hidden — at least initially — below the box (as set in the CSS):

JavaScript:
  1. $(document).ready(function(){
  2.   headline_count = $("div.headline").size();
  3.   $("div.headline:eq(" + current_headline + ")").css('top', '5px');
  4. });

The code examples for this entry used to include the .top() method, which, as of jQuery 1.1, no longer works. You will need to use .css('top', 'Npx') instead.

Before we move on, I'd like to point out a few things about the above code:

  1. jQuery has a .size() function that is similar to JavaScript's length property in that it returns the number of jQuery objects defined by the $() that comes before it.
  2. The second line is only fired once, when the DOM is first loaded. Instead of setting every headline's top to 5px, it uses a special jQuery DOM selector, :eq(), to set only the current headline's top. Typically, :eq() would take a number, like so: $("div.headline:eq(0)").
  3. I chose to pass in the "current_headline" variable instead of a number to allow for a little flexibility. If I later decide I want to start with the fourth headline, for example, I'd just have to change var current_headline = 0 up at the top of the script to var current_headline = 3. In order to get the variable in there, though, I had to concatenate it with the rest of the selector before and after it.

Everybody Rotate!

Now that everything was in place, I could write my headline_rotate() function. I first needed to increment each headline by one until I reached the last one and then start over, creating a loop. To do so, I used what my friend Jonathan Chaffer told me is called "clock arithmetic." Here is what that looks like (at least, the way I did it):

JavaScript:
  1. function headline_rotate() {
  2.   current_headline = (old_headline + 1) % headline_count;
  3. }

Line 2 sets a new value for current_headline by first adding 1 to old_headline and then using the modulus operator (%) to get the remainder of old_headline + 1 (our new headline) divided by headline_count (total number of headlines). Jonathan explained it this way: "the remainder will always equal old_headline + 1 until it reaches headline_count, at which point the remainder becomes zero." The only thing better than having a genius working next to me is having a genius who is great at explaining things to mere mortals like me. :)

Add the Animation

Next I added the animation into the headline_rotate() function — moving the old headline up and out of sight while moving the next headline (now called current_headline) into view.

The old headline movement actually has two parts: (a) scrolling up and out of sight and (b) moving instantly back down underneath the box so that it's ready to slide up into the box again the next time. This is where jQuery's "callbacks" come in very handy. I could queue the second effect by putting it in the callback of the first. Compare just the first effect...

JavaScript:
  1. $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow")

...to the first, plus the second in the callback...

JavaScript:
  1. $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow", function() {
  2.     $(this).css('top', '210px');
  3. });

By the way, the -205 in .animate({top: -205}) means that the top of the headline moves to 205 pixels above the top of its containing element (because the containing element had its position set to relative) so that we're sure the entire headline clears the box.

For the current headline, I simply moved its top up to 5 pixels below the top of the scrollup box so that it would be visible. And after that, I made old_headline equal current_headline:

JavaScript:
  1. $("div.headline:eq(" + current_headline + ")").animate({top: 5},"slow");  
  2.   old_headline = current_headline;
  3. }

To get the function to run when the page loaded, I simply dropped headline_rotate() inside my $(document).ready(). Unfortunately, that only made the animation fire once. I wanted it to repeat.

And Repeat

Remember that headline_interval variable I included way at the top? Here is how I used it:

Still inside $(document).ready(), I replaced headline_rotate() with headline_interval = setInterval(headline_rotate,5000);. That made JavaScript's setInterval() trigger my headline_rotate() function once every 5000 milliseconds (5 seconds).

Bonus – Pause on Hover!

I was fairly satisfied with the way the headline rotator worked, but I realized that for it to be really useful I'd want to make it pause when the mouse would hover over the box and start up again as soon as the mouse went back out. I'm not sure that I did it the best way, but it seems to have worked fairly well for me. I attached jQuery's hover() method to the "scrollup" div. The hover() takes two arguments, the first for mouseover and the second for mouseout. In the mouseover part, I stop the "interval," and in the mouseout part, I started it back up and called headline_rotate() again so the next headline would show up immediately:

JavaScript:
  1. $('#scrollup').hover(function() {
  2.   clearInterval(headline_interval);
  3. }, function() {
  4.   headline_interval = setInterval(headline_rotate,5000);
  5.   headline_rotate();
  6. });

That hover stuff also went inside $(document).ready(), and then I was done!

The Full Code

I set up a demo page with the full code and CSS embedded in the <head>, so if you want to take a look and copy it for your own use, go ahead. Or, take a look at the full jQuery code below:

JavaScript:
  1. var headline_count;
  2. var headline_interval;
  3. var old_headline = 0;
  4. var current_headline = 0;
  5. $(document).ready(function(){
  6.   headline_count = $("div.headline").size();
  7.   $("div.headline:eq("+current_headline+")").css('top', '5px');
  8.  
  9.   headline_interval = setInterval(headline_rotate,5000);
  10.   $('#scrollup').hover(function() {
  11.     clearInterval(headline_interval);
  12.   }, function() {
  13.     headline_interval = setInterval(headline_rotate,5000);
  14.     headline_rotate();
  15.   });
  16. });
  17. function headline_rotate() {
  18.   current_headline = (old_headline + 1) % headline_count;
  19.   $("div.headline:eq(" + old_headline + ")")
  20.     .animate({top: -205},"slow", function() {
  21.       $(this).css('top', '210px');
  22.     });
  23.   $("div.headline:eq(" + current_headline + ")")
  24.     .animate({top: 5},"slow");  
  25.   old_headline = current_headline;
  26. }

If you have any questions about the code or suggestions for improvement, please leave a comment.

UPDATE

Jonathan Chaffer and I wrote a much-improved version of this headline reader and discuss it in detail in the Learning jQuery book.You can see a demo of it on the companion site. Also, Mike Alsup has written the brilliant Cycle plugin that does the scroll-up effect and much, much more. Check it out!

comment feed

112 comments

  1. Erin

    I really like your tutorials! Wish there were more of them!

    One observation: It seems inefficient to continuously create new jQuery objects:$("div.headline:eq(" + current_headline + ")") Can't you just create one and then somehow access the different headlines within it?

    Here's a suggestion for future tutorials: I've been trying to understand the code behind some of the more popular plugins (at jquery.com) such as Accordion http://fmarcia.info/jquery/accordion.html and sometimes they are written at such a high level that there are parts I just don't understand. If you could take a pluggin and explain how it works (line by line) it would be great!

  2. Hi Erin, thanks for the comment and the suggestions! You may be right about the inefficiency of creating the jQuery objects; I'll have to look into that.

    I wish there were more of the tutorials, as well. :) And there will be, as time goes on. The blog is still in its infancy, so stay tuned. Good idea about looking "behind the scenes" of popular plugns. I'll try to add that to the list of upcoming entries.

  3. Erin

    How about this:

    var headline_count;
    var headline_interval;
    var old_headline = 0;
    var current_headline=0;
    var headlines = new Array(); // an array of jQuery objects
    $(document).ready(function(){
      headline_count = $("div.headline").size();
      for (var i = 0; i < headline_count; i++) {
        headlines[i] = $("div.headline:eq("+i+")");
      }
      headlines[current_headline].top('5px');
      headline_interval = setInterval(headline_rotate,5000);
      $('#scrollup').hover(function() {
        clearInterval(headline_interval);
      }, function() {
        headline_interval = setInterval(headline_rotate,5000);
        headline_rotate();
      });
    });
    function headline_rotate() {
      current_headline = (old_headline + 1) % headline_count;
      headlines[old_headline].animate({top: -205},"slow", function() {
        $(this).top('210px');
        });
      headlines[current_headline].show().animate({top: 5},"slow");
      old_headline = current_headline;
    }
  4. Erin, that looks good to me. Thanks again!

    By the way, I dressed up your comment's code a bit and deleted the first two failed attempts for you.

  5. Erin

    Thanks Karl. The code was truncating at the "less than" in the for loop.

  6. ShevKen

    Can you whip out a version which allows display of multiple headlines instead of 1-by-1.

    such as

    http://javascript.internet.com/text-effects/ajscroller.html

  7. Sure can, Kevin. It might take me a while to actually get to it, but look for a new entry sometime next week.

  8. ShevKen

    Thanks Karl. Looking forward to it!

    The ability to manipulate headlines directly in html instead of in the javscript really attracts. Gd job.

  9. hi karl, your single line scroller is pretty neat (i've integrated it with a project in cakephp). i'd also be interested in a means to scroll multiple headlines. will look out for an update soon :D

  10. Thanks, Mike. Glad you like it. The multi-headline scroller is a bit trickier than I had thought at first, because of the headlines' varying heights. I will definitely post an entry on it, but it might be a while before I can get to it and give it some sustained thought.

  11. It was originally meant to be used on http://www.intuit.com. Unfortunately, I think they removed it after I left. I kept a copy here. Check the bottom right box.

    It is a great widget. Well done!

  12. bergdog

    Oh, it's wonderful! I'm a JavaScript beginner and also a jQuery beginner, but I could really understand what you say, even though my mother language is Chinese, thank U!!!

  13. victor

    Hi Karl,

    Seems that your demo page example (http://test.learningjquery.com/scrollup.htm) doesn't work neither in Firefox nor in Opera (only in IE). At the same time an example at the beginning of this article works fine. Any explanation?

  14. Hi Victor, thanks for notifying me of the problem with the demo page. I wrote the script last fall before version 1.1 and its API change. Before 1.1, we could use a shorthand method such as .top() in place of .css('top'), but those shorthand methods have been removed.

    I updated the demo script on the test site, so it should be working just fine now. Thanks again for catching the problem.

  15. tomasz

    Nice script !
    But it would be nice with a 'previous' and a 'next' button to skip the news :)

  16. We did a website based off this script except that our news has a counter:

    1 of 10

    a "pause" and "next" buttons. You can see it in action here:

    http://www.crestwoodbaptist.org/

    source code available from the site using "view source" :)

  17. Markus

    Hi,

    i look for a script like this, thx.
    But one question:

    When a User has JS off in the Browser nothing will display. Is there e way with JS off that all News will display with a vertical scrollbar?

    Sry for my poor english...

    greetings Markus

  18. Markus, I'm really glad you asked that question. This script should definitely degrade better than it does. Here is one way you can make it look good without JavaScript:

    1. make these changes (in bold) to the stylesheet

    #scrollup {
      border:1px solid #000;
      height:200px;
      overflow:auto;
      position:relative;
      width:200px;
    }
    .headline {
      height: auto;
      left: 5px;
      position: relative;
      top: 5px;
    }

    2. Then, to get it looking sharp again with JavaScript, replace this line:

    $("div.headline:eq("+current_headline+")").css('top','5px');

    with this:

    $('#scrollup').css({position: 'absolute', overflow: 'hidden'})
    $('div.headline')
    .css({position: 'absolute', height: '195px'})
      .not(current_headline)
      .css('top','210px');

    Let me know how that works for you.

  19. Randy, Nice work on your variation of the script. I like your additions!

  20. Markus

    Hi Karl,

    thx for help. I will try it later.

    Now i found a littel "Bug". Using IE7 and move the mouse over the scroller he didn´t stop. When moved the mouse in the scroller to any direction it looks crazy... ;)

    mfg Markus

  21. Alex

    Is there a version of this that would use an unordered list instead of a stack of nested DIVs?

  22. Hi Alex. I haven't written a version that would use an unordered list instead, but I don't think it would be hard to modify this one. If you used <ul id="scrollup"> and <li class="headline">, then I think it would mostly be a matter of modifying the CSS a bit and changing references to "div.headline" in the code to "li.headline"

    If you'd like to give that a whirl, feel free to contact me if you get stuck along the way.

  23. Hi Karl, thanks alot for your tutorial...
    i ve modified your code a bit, i ve changed divs to unordered list and vertical scrolling to horizontal scrolling.
    here is the modified version:
    http://www.emrecamdere.com/news_scroller_jquery.html
    i hope it ll be useful for someone

  24. Nixdama

    it not works on IE7

  25. Zoo

    I am looking for a code that scrolls up, pauses, then scrolls news to the left or right, then with the next news story it scrolls up, pauses, then scrolls news to the left or right again. Can the two codes mentioned be combined in someway to accomplish this action? Thanks for the tutorial!

  26. Laurent

    Hi!
    First of all, thanks for this very useful script.
    I've got a problem with Flash. Have you ever tried to include an swf object in one of the headlines? While it works in IE7, the flash animation gets stuck in the bottom of #scrollup in Firefox and doesn't scroll. I imagine that your script is not to blame but the way Firefox interpret the object tag but if by any chance, you've encountered the problem...
    Once again, thanks for your work and have a nice day ;-)

  27. Hi Laurent,
    I'm sorry, but I have very little experience with Flash. You might have better luck with Mike Alsup's Cycle plugin. It's very solid with tons of features.

  28. Mike

    thank you for your straightforward and functional tutorial

  29. Bhaarat

    Hi Karl,

    Thanks a LOT for this. I never knew about jQuery! but this really is like magic!! Cant wait to go home and get my hands dirty with this. Also, do you know if the dzone scroll functionality where more headlines are loaded as the user is about to reach the end of the page is also done in jQuery?

    If you have some code that would kind of show how to achieve that it would be wonderfull!!

    Thanks for this!!

  30. tracert

    Hi Karl,

    Thank you for the script, it's very nice. But I have a problem.
    I use the toggle() function to display and hide the headline div. When I click on the link (which hides the headline div), and click again (displays the headline div again), it starts rolling again, but it looks like this: picture

  31. Hi all. i´m Miguelito ( newbe in jQuery from Spain)

    I have to do a continuos scroll function to a div with html structure like this:
    div-class listaScroll) ul li li li li /ul /div
    each li has html inside ( news to scroll)

    it works, but surelly you can hep me with some 'bugs'

    1.- Rest-of-the-page-links does not work if i do not 'stop' the timer properly

    2.- multiple divs in same page scrolling: scrolls at same time, stops in same time :(

    any ideas ?

    URL: my site (i´m modifiyng it)

    Thanks for your time!.

    ( I´m using jquey.timer.js for timers, but maybe innecesary, or maybe it´s the problem. I´m new with jquery timer events :) )

    CODE:


    jQuery(document).ready(function(){
    initScroll();
    jQuery(".listaScroll ul li a").hover( stopScroll, initScroll);

    function initScroll(){
    jQuery(".listaScroll").everyTime(3000, 'miTimer', scrollUp);
    }
    function scrollUp() {
    var elemParent=jQuery(this).find("ul:eq(0)").get();
    jQuery(elemParent).find("li:eq(0)").hide(2000, function(){
    jQuery(this).appendTo(elemParent).show(); //mode element to the end
    });
    }

    function stopScroll(){
    jQuery(".listaScroll").stopTime("miTimer");
    }

    jQuery("a").click( function(){ // ehem... it stops the scroll, so the links work again...
    stopScroll();
    return true;
    });

    });

  32. Catalin Oltean

    How I can make script to work with an external scrollup div inserted in document with Ajax?

  33. Catalin Oltean

    How I can make script to work with a scrollup div that contain an external html file inserted in document (div) with Ajax?

  34. if we put dynamic content...how we handle height thing...

    mean how height should be auto fitted to each loading....because in my case that viewing area should be changed with it loaded no of items...so..how can we handle that kind of thing...pls tell me thanks

  35. This is what's I looking for, I have a question.
    How to integrated this code with this effect

    http://www.malsup.com/jquery/cycle/begin.html

    Please Help me and thanks

  36. very good tut, it really help me, thanks!

  37. i have used the headline scroller on a couple of pages with good success. However, on 2 of my pages, when the page is visited, all of the headlines show up at first and after the first interval they scroll correctly. you can see what i mean here at
    http://www.axessnetwork.com and;
    http://www.buckstoparchery.com

    also, on the buckstop archery site, i have a flash element in the scroller. When opened with Mozilla Firefox, the flash element shows up constantly just below the div area. Can anyone advise? Thanks.

  38. Hi Josh,
    on the axessnetwork site, you can probably fix the problem by changing this:

    $("div.headlines:eq("+current_headline+")").css('top','5px');

    to this:

    $("div.headlines:eq("+current_headline+")").css('top','5px')
        .siblings().css('top','210px');

    I don't see the problem with the Flash element in FF3 Mac, but one thing you might want to try is to set the Flash object's "wmode" property/attribute to "transparent."

  39. Thanks for the help. That made all the difference. I am not sure why it loaded all the info into the DIV at once. I have used this script on numerous sites and those are the only 2 that i had problems with. The .siblings rule cleared it up. Thanks.

    Josh

  40. Ryan

    Hi all, I'm pretty new to JQuery, and I've found the final demo, the "go ahead" link to not work. All I get is an empty box. Same thing happens when I put the above code into my test page. Can anyone help? Thanks in advance.

    Ryan

  41. Hi Ryan,
    Sorry about that. Apparently, some change in the way Feedburner is set up broke my php script to pull the xml file into my domain before parsing. I'm using an old, static, xml file now for the purpose of the demonstration. Thanks for calling this to my attention.

  42. nick

    Is there a way to keep the text from pausing at the top for a smooth continuous scroll? thanks!

  43. Hello all,
    once again, i cut and pasted the code into my site, however, the scroller will not scroll. I have looked the code over many times but cannot figure out the reason. Can anyone assist? Thanks.

    Josh Henry

  44. Hi Josh,
    Do you have a link to the page where you included the code? Are you getting a JavaScript error? Definitely use the Firebug extensions for Firefox. That will help you debug.

  45. sorry, i thought the website would post from the input field. It is http://www.mebaptist.org

  46. Hi Josh,
    You only have one <div class="headline"> in there. Add a couple more and you'll be able to see them scroll up.

  47. Can anyone give me somd idea of what I've done wrong here?

    http://vm2-wb1.uts.columbia.edu/scrollup_afund.html

    I am very new to jQuery.

  48. Hi Jim,
    If you use Firebug with Firefox (which you should), you'll see that there is a "$ is not defined" error. It looks like you're pointing to a non-existent jquery.js file. Make sure you grab a copy of jquery.js and put it in the correct location on your server.

  49. I am using php to pull from my MySQL DB into the scrollup div in a headline field. I am using a repeat region to pull the multiple items from the DB. I have this working on another site, http://www.pointeoasis.com/upcoming.php. I cut and pasted the code into my new site, http://www.mebaptist.org but the scrolling action does not work. I have looked over the code line by line to see what is wrong but cannot figure it out. Can you assist? Thanks in advance.

  50. Hi Josh,

    The script at http://www.mebaptist.org/ isn't wrapped in a $(document).ready() function. That's probably why it isn't working.

  51. How would i change that to wrap it in the $(document).ready() function?

  52. Ah, forget about that. I see that you already have document ready in there. It has been a long time since I looked at this script. Sorry.

    The one thing you didn't copy/paste, though, is the CSS. When I inspected the headline elements in Firebug, it looked like the JavaScript was working fine—the "top" property was being animated successfully. So, just grab the CSS from post, and you should be fine. In particular, you'll need the containing element to be position: relative and overflow: hidden, and the headline elements to be position: absolute.

  53. Thanks for the response. I just edited the css to reflect your recomendations. It still is not scrolling as it should. Can you assist a bit further? Thanks.

  54. You have position: abosolute;. Change that to position: absolute;. Also, you're going to have to set a height on the headlines as well to match the height of the containing element. It's all at the top of this entry in a nicely formatted code block, but here it is again:

    #scrollup {
      position: relative;
      overflow: hidden;
      border: 1px solid #000;
      height: 200px;
      width: 200px
    }
    .headline {
      position: absolute;
      top: 210px;
      left: 5px;
      height: 195px;
      width: 190px;
    }
    
  55. Kurt,

    thanks for your patience. I have written in the necessary CSS code but still cannot get the information to scroll. Its almost as if it is not recognizing the area to be scrolled.

  56. Hi Josh,

    It looks like you still haven't fixed the position: abosolute; typo. When you change that to position: absolute; it should work.

    p.s. I'm Karl, not Kurt. :)

  57. Thanks so much Karl,

    my apologies, today has been a crazy day especially with them wanting this site to be working. I greatly appreciate your help.

  58. Kelly

    Hi Guys. First sorry for my bad english. I am spanish.
    I reach here googling and i find this tutorial very interesting, but i have a litle question, can i define one specific category to show in the headline reader, i mean i just wanna show some posts in the headline reader not all the posts of my blog. kisses ;)

  59. J

    Awesome script. Was there ever a solution to scroll multiple lines at once?

  60. oMat

    Thanks for the efforts.

    One problem is, the scrolling acts crazy when hovered in IE, as mentioned by other users in this thread. Any solution for that yet?

    Thanks.

  61. Thanks! Great article.

  62. Hi,

    Another great script. However, I've modified the CSS so it only shows one line for a headline to fit in the site that I've built. The problem is that when you rollover the headline or the div and roll off, it quickly jumps to the next headline, is there anything that can prevent that from happening? So it scrolls only on the automatic timer thingymigig thats set? I presume its to do with the .hover function on line 11 in your example above?

    Thanks

    :)

  63. Stu

    Hi,

    Great scroller, is it possible to have two instances of this scroller working on the same page?, i have built a test page but when there are two or more scrollers on the same page they work 1 @ a time,

    thanks

  64. ivan

    Would it be possible to add 'next' and 'previous' links to scroll faster around news? - if so, would anyone be to give me a clue on how to do this? THanks!

    • Hi Ivan,
      Check out these demos of Mike Alsup's Cycle Plugin. I would definitely encourage you to use that plugin, as it is incredibly flexible with lots of options and it has been extensively tested in the wild.

  65. Hello! Great code. I am new to coding, but I was able to get the basic version to work with the hover function masked out. I cannot get it to work when I change the current_headline variable. When I plug three instead of zero as in your example above, the correct headline appears first, but then it does not go away. All successive headlines show up over it until its number comes up and then it flies off the page. Is the current_headline variable hidden somewhere else to fly up and off the page?

    Here is the code I'm using:

    var headline_count;
    var headline_interval;
    var old_headline = 0;
    var current_headline = 3;

    $(document).ready(function(){
    headline_count = $("div.headline").size();
    $("div.headline:eq("+current_headline+")").css('top', '5px');
    headline_interval = setInterval(headline_rotate,5000);

    //$('#scrollup').hover(function() {
    // clearInterval(headline_interval);
    //}, function() {
    // headline_interval = setInterval(headline_rotate,5000);
    // headline_rotate();
    //});
    });

    function headline_rotate() {
    current_headline = (old_headline + 1) % headline_count;
    $("div.headline:eq(" + old_headline + ")")
    .animate({top: -205},1000, function() {
    $(this).css('top', '210px');
    });
    $("div.headline:eq(" + current_headline + ")")
    .animate({top: 5},1000);
    old_headline = current_headline;
    }

    (Sorry if this isn't formatted the way you wanted, I'm not sure what those directions mean.)

  66. I made a WordPress plugin based on this. It's my first one ever, and I absolutely could not have done it without this demonstration. I give credit where credit is due, Karl! The plugin description has a link to this page.

    Thanks again, and you can get the plugin here.

  67. Ken

    Very nice tutorial. I was trying to get continuous horizontal scrolling that shows more than one story, until the first stories just disappear into the top of box. Is there a way to show more then one story at a time and have them all just scroll up?

  68. hello,

    this is really cool, can any one help what i need is that the text inside should be paused
    and when you hover with mouse it should animate....

  69. josefk

    Thanks Karl - these tutorials are marvelous - and gentle too! It's really nice that you keep the articles fresh by adding more comments too.

    Re: Alex's question on using unordered lists (comment 21): the added structure would make the code more usable for screenreader users too...

  70. Shazwi

    Gosh I need help !!! This is so frustrating, nothing even appears in my output lol.

    jQuery Experiments

    var headline_count;
    var headline_interval;
    var old_headline = 0;
    var current_headline = 0;

    $(document).ready(function(){
    headline_count = $("div.headline").size();
    $("div.headline:eq("+current_headline+")").css('top','5px');

    headline_interval = setInterval(headline_rotate,5000);
    $('#scrollup').hover(function(){
    clearInterval(headline_interval);
    }, function(){
    headline_interval = setInterval(headline_rotate,5000);
    headline_rotate();

    });

    });
    function headline_rotate()
    {
    current_headline = (old_headline + 1) % headline_count;
    $("div.headline:eq("+old_headline+")")
    .animate({top: -205},"slow",function(){
    $(this).css('top','210px');

    });
    $("div.headline:eq("+current_headline+")")
    .animate({top: 5px},"slow");
    old_headline = current_headline;
    }

    #scrollup
    {
    position: relative;
    overflow: hidden;
    border: 1px solid black;
    height: 200px;
    width: 200px;
    }
    .headline
    {
    position: absolute;
    top: 210px;
    left: 5px;
    height: 195px;
    width: 190px
    }

    WHAT THE FUCK

    Breaking News 1!
    Breaking News 2!
    Breaking News 3!
    Breaking News 4!

  71. Shazwi

    Theres a big problem with this code... When I hover a lot of times, the thing just scrolls sooo fast... Shouldnt there be a stop() thing after animate() to prevent this...

  72. jasmit

    hi

    at present, everytime i hover on it, it stops and starts when i move cursor out. like if in 5 seconds i hover on it 5 times, then it will stop 5 times and onmouse out the scroll moves up 5 times.

    means it should not animate everytime i hover-in and hover-out in 5seconds and also should not animate till the mouse is on it.

    It should animate only on set interval with the condition that mouse is not on it.

    jasmit

  73. I followed the hint has given above, but i didnt get any output. Just it is showing a rectangular box only.The following is my code, pls review it and advise me.

    Note: anything else we have to install/add for Jquery.

    Untitled Document

    var headline_count;

    var headline_interval;

    var current_headline = 0;

    var old_headline = 0;

    $(document).ready(function(){

    headline_count = $("div.headline").size();

    $("div.headline:eq(" + current_headline + ")").css(top, '5px');

    });

    function headline_rotate() {

    current_headline = (old_headline + 1) % headline_count;

    }

    $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow");

    $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow", function() {

    $(this).css('top', '210px');

    });

    $("div.headline:eq(" + current_headline + ")").animate({top: 5},"slow");

    old_headline = current_headline;

    }

    $('#scrollup').hover(function() {

    clearInterval(headline_interval);

    }, function() {

    headline_interval = setInterval(headline_rotate,5000);

    headline_rotate();

    });

    headline1 ...

    headline2...

    headline3...

    headline4 ...

  74. I followed the hint has given above, but i didnt get any output. Just it is showing a rectangular box only.The following is my code, pls review it and advise me.

    Note: anything else we have to install/add for Jquery.

    
    < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    < html xmlns="http://www.w3.org/1999/xhtml">
    < head>
    < meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    < title>Untitled Document< /title>
    < script>
          var headline_count;
          var headline_interval;
          var current_headline = 0;
          var old_headline = 0;
          $(document).ready(function(){
            headline_count = $("div.headline").size();
            $("div.headline:eq(" + current_headline + ")").css(top, '5px');
          });
          function headline_rotate() {
            current_headline = (old_headline + 1) % headline_count;
          }
    $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow");
          $("div.headline:eq(" + old_headline + ")").animate({top: -205},"slow", function() {
              $(this).css('top', '210px');
          });
          $("div.headline:eq(" + current_headline + ")").animate({top: 5},"slow");
            old_headline = current_headline;
          }
          $('#scrollup').hover(function() {
            clearInterval(headline_interval);
          }, function() {
            headline_interval = setInterval(headline_rotate,5000);
            headline_rotate();
          });
    < /script>
    < style type="text/css">
    < !--
          #scrollup {
            position: relative;
            overflow: hidden;
            border: 1px solid #000;
            height: 200px;
            width: 200px
          }
          .headline {
            position: absolute;
            top: 210px;
            left: 5px;
            height: 195px;
            width:190px;
          }
    -->
    < /style>
    < /head>
    < body>
          < div id="scrollup">
            < div class="headline">headline1 ... < /div>
            < div class="headline"> headline2... < /div>
            < div class="headline"> headline3... < /div>
            < div class="headline">headline4 ... < /div>
          < /div>
    < /body>
    < /html>
    
    • Jeffrey

      You might want to download jQuery and include it in your page... before the script

    • Randy

      $("div.headline:eq(" + current_headline + ")").css(top, '5px');

      You are referencing top as an object, not as a literal. Change to:

      $("div.headline:eq(" + current_headline + ")").css('top', '5px');

  75. Thank you, this tutorial has me very helped.

  76. To fix the issue with the mouseovers (eg if you mouse over, then away, it kickstarts the scrolling again.. moving the mouse around a bit repeatedly makes it initiate the scroll function too much, overlapping itself).. just change:

    
      $('#scrollup').hover(function() {
     clearInterval(headline_interval);
      }, function() {
     headline_interval = setInterval(headline_rotate,5000);
      headline_rotate();
      });
    

    to

    
      $('#scrollup').hover(function() {
     clearInterval(headline_interval);
      }, function() {
     headline_interval = setInterval(headline_rotate,5000);
      });
      headline_rotate();
    

    Then it won't manually kickstart the scroller everytime the mouse is moved over the box.. instead just initiating it once and letting the mouseover/mouseout purely change the timing variable.

    Thanks for the script as well.. while i'll probably end up going with the Cycle plugin for the effects, I like the simplicity of this so will no doubt use it in the future..

  77. Thank you ... that has me very helped.

  78. Taruna

    Hi is there anyone to help me, i tried following up and i doesn't work for me. I have pasted the code above the jquery file. I have got the styles in my css file. I have the following divs in my html file. I hope I am not missing on anything other than this.

  79. Taruna

    Hi is there anyone to help me, i tried following up and it* doesn't work for me. I have pasted the js code above the jquery file. I have got the styles in my css file. I have the following divs in my html file. I hope I am not missing on anything other than this.

    • Hi Taruna,
      It looks like your code didn't come through. If you're having a problem getting something to work, please provide a link to the page where you're experiencing the problem.

      thanks.

  80. Hi Karl.
    Excellent script works like a charm !
    I am fresh to jquery programming, so my question is :
    is it possible to update elements from regular javascript ( name.innerHTML or document.write ) to make it a dynamic content ? i.e load it from XML file ?
    Regards.

  81. in the previous post i ment to upade &ltdiv&gt elements

  82. alon

    thanks alot !!
    I was looking for that kind of script alot of time ! and even without a plugin.
    just perfect, thanks.

  83. thanks alot !!
    I was looking for that kind of script alot of time ! and even without a plugin.
    just perfect, thanks.

    I will use it on my site :)

  84. Jason

    how can i do for more than one headline rotator ?
    ex.

    
        Headline 1
        Headline 2
        Headline 3
        ....
        Headline 1
        Headline 2
        Headline 3
        ....
    

    i was try with "each" but can't done succes

    Thanks

  85. Lance

    Very helpful, thank you

  86. Hi,

    Demo page not working.
    Message:
    Not Found

    The requested URL /scrollup.htm was not found on this server.

  87. I've spent many hours trying, different variations trying to get scroll-up-headline-reader to work but nothing happens. "The go head" page doesn't exist, therefore I can't benefit like those whom got the code to work. I just got fed up and bought this wonderful Newscroller at news-scroller.com

    It was only $35.00. Also you can download the free demo before buying. It appears to be easy to use. You'll have it up and running less than 20 minutes. It has a easy interface for color styling, HMTL, fade in, scrolling speed control and much, much more. No coding headaches. You simply FTP a HTML and a Javascript file onto your web host server and use the short code provided, to put any where on your website. That's it!

    Stop wasting time. You make the choice.

    • Bruce, if you believe that learning something is a waste of time, then by all means spend your $30 and have your fun. Sorry the demo page was 404ed. It's a three-year-old post, and I switched web hosts during that time due to my account being hacked, so I've had to painstakingly recreate a lot of files that were lost. That said, I linked to the full JavaScript at the end of the post and I provided all the html and css you need in various codes blocks throughout the post. I also show a running example in the post, linked to another demo on a book companion site (here's another one), and recommended that people check out Mike Alsup's fantastic, free Cycle Plugin. If that's not enough for you, then too bad. Apparently you made your choice. Now stop wasting my time.

  88. Arun

    Hello karl

    thanks for the post,

    I'm new bee to jquery i want to learn jquery.

    I tried this example step by step but the result is not shown in browser, pls help me out.....
    Is there need to attach any external file.......?

    I'm waiting for your reply...

    Thanks

  89. Andy

    Hi Karl,

    Great little scroller here, just one question do you know how I could I get the info for the scroller from an external file either html or php. What I want to do to be clear is as follows.

    On one page the scroller, pull viewed info from another file.

    If not do you know of any tutorial which would do this sort of thing as I would like to learn

    Kind Regards Andy.

  90. Hi,

    i want to show more then 1 Head lines in a container, current ur demo is showing for one head line , one by one. i want :

    1 2 3
    231
    312
    123

    so suggest me modify code for that , how i can display 3 Headlines News on display

    pl help

    • Probably the easiest way would be to wrap each set of three headlines in a div element. Then you can use CSS to style the headlines within each div the way you want them to appear.

  91. Stephan Ivaylov

    Hi Karl,

    I really can't get which part of the code is in charge for the cycling?
    I mean all this functions to be called again for every iteration.
    Is it only the "setTimeout()" method responsible?

    • In the code above, the headline_interval variable is assigned to a setInterval function. That setInterval function executes the headline_rotate function every 5000 milliseconds (or 5 seconds):

      headline_interval = setInterval(headline_rotate,5000);

  92. SMS

    In FF I moved the mouse pointer in and out of the box real fast several times...interesting results. You shouldn't have to care about people being careless like that, but you could probably easily code a fix to prevent it.

  93. If I want to use the same function for other boxes on the same page, how do I add a different id in the script? Otherwise I should load different scripts and css for each box. I used a method, but does not work. Can you tell me how to improve the script suggesting this?

    
    headlineId = $(this).attr('class');
    headline_count = $("div."+headlineId+"_hl").size();
    otherwise
    headlineId = $(this).attr('id');
    headline_count = $("#"+headlineId+"_hl").size();
    

    Thanks

  94. Keith

    Did anyone get Markus's post #17 and Karl's reply post #18 working?

    It works when JS is disabled, all the headlines appear with a vertical scroll bar. But with JS enabled the first headline is not appearing until the first time through the setInterval time.

    I think is has something to do with css "Top" property, but I'm not 100% sure. It looks as if it is starting with top set to 320px, which displays nothing.

    Code:
    #scrollup {position: relative; overflow: auto; height: 320px; }
    .headline {position: relative; top: 5px; left: 0; overflow: hidden; height: auto;}

    $(document).ready(function(){
    headline_count = $("div.headline").size();
    $('#scrollup').css({overflow: 'hidden'})
    $('div.headline')
    .css({position: 'absolute', height: '320px'})
    .not(current_headline)
    .css('top','320px');
    headline_interval = setInterval(headline_rotate,2000);
    });

    function headline_rotate() {
    current_headline = (old_headline + 1) % headline_count;
    $("div.headline:eq(" + old_headline + ")")
    .animate({top: -325},"slow", function() {
    $(this).css('top', '330px');
    });
    $("div.headline:eq(" + current_headline + ")")
    .animate({top: 5},"slow");
    old_headline = current_headline;
    }

  95. Randy

    Hi Karl,

    In the code snippet just above the jQ1.1 .top() deprecation warning

    .css(top, '5px')

    should be

    .css('top', '5px')

    Guess I'm the only one that does cut/paste from the snippets instead of the final complete example.

    Regards

  96. Hey.. I am a designer and willing to be a developer as well.. I followed this step by step tutorial but it is not scrolling.. then I moved to that demo page and followed the script and it started to worked with that.. the code you mention here is different from the code of that demo page.. anyway I enjoyed it :)

6 Pings

  1. [...] product and public site this week.  Uses a bunch of jQuery, Tabs Plugin, Validation Plugin and Scrolling Promo Effect.  Design was done by Sean Zimmerman.  HTML Production was done by NetKitchen and myself.  [...]

  2. [...] Learning jQuery » Scroll Up Headline Reader (tags: jquery scroller) [...]

  3. [...] coding tips and tricks, C#, .NET, ASP.NET, SQL, default text, jQuery trick, default text input Learning jQuery » Scroll Up Headline Reader Creating a Dynamic Poll with jQuery and PHP - NETTUTS Submit A Form Without Page Refresh using [...]

  4. [...] new image just to include a story in their front page rotator. So I started looking, and I found a JQuery site that had an interesting [...]

  5. [...] A really simple newsfeed scrolling display – at time of writing only displays one item at a time, but the author intends to write a multi-item display version before long: http://www.learningjquery.com/2006/10/scroll-up-headline-reader [...]

  6. [...] from the FrontPage category and rotates their titles and excerpts using a JQuery scroller. Based on Scroll Up Headline Reader by Karl [...]

Sorry, but comments for this entry are now closed.