How to Build a Simple News Scroller
videos

How to Build a Super Duper News Scroller

This week, we’ll learn how to combine PHP, SimplePie, and jQuery to build a simple news scroller widget for your website. It’s much easier than you might think; so let’s begin.

Note that I modified the code slightly after recording this screencast. Don’t worry, they’re just minor changes; but as with anything, you should continuously refactor your code.

Final Product

Final NewsScroll Plugin

(function($) {

$.fn.newsScroll = function(options) {

	return this.each(function() {	

		var
		  $this = $(this), 

		  defaults = {
		  	speed: 400,
		  	delay: 3000,
		  	list_item_height: $this.children('li').outerHeight()
	     },

		  settings = $.extend({}, defaults, options); 

	  setInterval(function() {
	  	    $this.children('li:first')
	  	    		.animate({
	  	    			marginTop : '-' + settings.list_item_height,
	  	    		   opacity: 'hide' },

	  	    		   settings.speed,

	  	    		   function() {
	  	 					$this
	  	 					  .children('li:first')
	  	 					  .appendTo($this)
	  	 					  .css('marginTop', 0)
	  	 					  .fadeIn(300);
  		 			  }
 	 			  ); // end animate
 	  }, settings.delay); // end setInterval
	});
}

})(jQuery);

With Commenting

// Create a self-invoking anonymous function. That way,
// we're free to use the jQuery dollar symbol anywhere within.
(function($) {

// We name our plugin "newscroll". When creating our function,
// we'll allow the user to pass in a couple of parameters.
$.fn.newsScroll = function(options) {

	// For each item in the wrapped set, perform the following.
	return this.each(function() {	

		var
		  // Caches this - or the ul widget(s) that was passed in.
		  //  Saves time and improves performance.
		  $this = $(this), 

		  // If the user doesn't pass in parameters, we'll use this object.
		  defaults = {
		  	speed: 400, // How quickly should the items scroll?
		  	delay: 3000, // How long a rest between transitions?
		  	list_item_height: $this.children('li').outerHeight() // How tall is each list item? If this parameter isn't passed in, jQuery will grab it.
	     },
	      // Create a new object that merges the defaults and the
	      // user's "options".  The latter takes precedence.
		  settings = $.extend({}, defaults, options);

	  // This sets an interval that will be called continuously.
	  setInterval(function() {
	  	    // Get the very first list item in the wrapped set.
	  	    $this.children('li:first')
	  	    		// Animate it
	  	    		.animate({
	  	    			marginTop : '-' + settings.list_item_height, // Shift this first item upwards.
	  	    		   opacity: 'hide' }, // Fade the li out.

	  	    		   // Over the course of however long is
	  	    		   // passed in. (settings.speed)
	  	    		   settings.speed, 

	  	    		   // When complete, run a callback function.
	  	    		   function() {

	  	    		   	// Get that first list item again.
	  	 					$this.children('li:first')
	  	 					     .appendTo($this) // Move it the very bottom of the ul.

	  	 					     // Reset its margin top back to 0. Otherwise,
	  	 					     // it will still contain the negative value that we set earlier.
	  	 					     .css('marginTop', 0)
	  	 					     .fadeIn(300); // Fade in back in.
  		 			  }
 	 			  ); // end animate
 	  }, settings.delay); // end setInterval
	  });
}

})(jQuery);

Final Page

<?php

require 'simplepie.inc';
$feed = new SimplePie('http://net.tutsplus.com/rss');
$feed->handle_content_type();

?>

<!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" />
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8" />
<title>Super Duper News Scroller</title>
</head>

<body>

<div id="container">
	<h1>Super Duper News Scroller: <small>Built With PHP, SimplePie, and jQuery</small</h1>

		<ul id="widget">
			<?php foreach($feed->get_items(0, 15) as $item) : ?>
			<li>
				<?php echo $item->get_description(); ?>
				<h4><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>
				<p>
					<?php echo $item->get_date(); ?>
				</p>
			</li>
			<?php endforeach; ?>
		</ul>
</div><!--end container-->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.newsScroll.js"></script>

<script type="text/javascript">
	$('#widget').newsScroll({
		speed: 2000,
		delay: 5000
	});

	// or just call it like:
	// $('#widget').newsScroll();
</script>

</body>
</html>

That’s It

In twenty minutes, we were able to build a nice and simple scroller. You’re now free to take the plugin and expand it to your needs. What you have here should be considered the first step. How can you improve upon it?

You Also Might Like…

  • Screenshot 1

    Extending SimplePie to Parse Unique RSS Feeds

    A few days ago, as I prepared our Create a Slick Flickr Gallery with SimplePie tutorial, it occurred to me that we haven’t posted many articles that covered SimplePie. Considering how fantastic a library it is, I think it’s time to take a closer look.

    Visit Article

  • Screenshot 1

    You Still Can’t Create a jQuery Plugin?

    It’s tough. You read tutorial after tutorial, but they all assume that you know more than you actually do. By the time you’re finished, you’re left feeling more confused than you initially were. Why did he create an empty object? What does it mean when you pass “options” as a parameter? What do “defaultsettings” actually do?

    Never fear; I’m going to show you exactly how to build your own “tooltip” plugin, at the request of one of our loyal readers.

    Visit Article

  • Screenshot 1

    jQuery for Absolute Beginners

    Hi everyone! Today, I posted the final screencast in my “jQuery for Absolute Beginners” series on the ThemeForest Blog. If you’re unfamiliar – over the course of about a month, I posted fifteen video tutorials that teach you EXACTLY how to use the jQuery library. We start by downloading the library and eventually work our way up to creating an AJAX style-switcher.

    Visit Article

  • Screenshot 1

    Diving into PHP: Video Series

    Today marks the beginning of a brand new series on the ThemeForest blog that will show you EXACTLY how to get started with PHP. Just as with the “jQuery for Absolute Beginners” screencasts, we’ll start from scratch and slowly work our way up to some more advanced topics. If you’ve been hoping to learn this language, be sure to pay a visit and subscribe to the RSS feed to be updated when new videos are posted.

    Visit Article

Add Comment

Discussion 94 Comments

Comment Page 2 of 2 1 2
  1. xxx says:

    Hi everyone,

    Great an a Nice News Scroller. Perfect for my Blog.

    later ….

    • joe says:

      wow cool tutoriall….. just wondering if this would work with any rss feed? the reason i ask is because how does it know to grab the image? for example, xxx rss feed company has news with images…. how does it know how to grab the images as well?

  2. Matthias says:

    Thank you, that’s perfect !

  3. Abubaker says:

    Thanks for sharing.. Excellent thing.. I was wondering that if we want to make the a widget with tabs, each tab having feeds from different news websites. How to implement this thing? please guide…

  4. Anders says:

    Have you noticed the bold headline when it moves in IE7 and IE8?
    Just before it starts to move the bold text looses the anti-aliasing. It can be seen in Kevins demo page here: http://work.kevinleary.net/newsScroller/

    Can this be fixed somehow?

  5. Anders says:

    I will answer my own question …

    There is a clear type bug in IE7 and one way to work around it is to add a background color. It wont completely remove the problem but it makes it much less obvious.

    In the example code above you should add a background color for #widget li

  6. LuK says:

    Thank you very much for the tutorial, appreciated the nicely commented code =)! I would like to implement a mouseover-stop-scrolling feature but I wasn’t really able to do so…here is an approach, do you mean this could be integrated somehow, it’s from the jquery tools scrollable plugin, they use this to stop autoscrolling their plugin.

    if (conf.interval > 0) {

    // when mouse enters, autoscroll stops
    root.hover(function() {
    clearInterval(timer);
    timer = 0;

    }, function() {
    setTimer();
    });

    setTimer();
    }

    thx for any answer!

  7. Hi all. First of all thanks for the plugin.
    I tried this with asp.net web page. @Dennis, I don’t think you need to bother using simple pie in asp.net. Any simple rss reader can do. Take jquery google feed plugin and then it is only some few lines to go with!

    Thanks again!

  8. If anyone needs to see the code, please contact me. Thank you.

    • Rob says:

      I’m assuming this only works in WordPress-themed sites…is that right?

      I couldn’t get the code to work with a Blogger feed; the “get_description” command brought the entire body of the post, along with the image inserted/associated with the individual post, and left out the “get_permalink” result (no title appeared or link). Actually, the picture was linked to itself, which I thought interesting.

      Note to others: It’ll work with Blogger, but will not work as fully as it does shown here. (or…that’s my take, anyway)

  9. Keith N says:

    What do you do if there are no images to pull from the reader?

  10. Awesome.. Excellent.. that is what I was looking for.. Hats Off to You

  11. Just a Quick Question, How would I change the Direction of the scroller? I want scroller should start from top and ends at bottom. any help would be highly appreciable

    Thanks
    Puneet

  12. Mr.Mark says:

    How can i change the content to just reflect anything that i put in there instead of the simplePie feed?

    I’m using WordPress with a plugin called “Event Calendar 3″. I want to let the list of events scrolling like ur feed in here.

  13. Rhett Forbes says:

    works like a charm

    Thanks
    Rhett

  14. Mr.Mark says:

    How is it possible that the items that are supposed to be hidden by `overflow: hidden` still show up in IE7?

    website: http://www.yugongyishan.com/events/ (slider is at the top of the sidebar)

  15. rob says:

    Is there some setting(s) in wordpress that you have to configure in order for this to show images in the post/scroller. I get the post, but no images.

  16. If you have to do it, you superiority as through do it right.

  17. c0mrade says:

    I don’t think the video is loading properly anymore..

  18. steve says:

    would love to see this implemented with tabs.
    I too would like to flip the scrolling direction if possible…

  19. Michael says:

    Hey great tutorial.

    The only problem im having is, i linked the news scroller to my WordPress blog and no images are showing on the scroller, how can i fix this?

  20. edp says:

    nice tuts..thanks

  21. Marc says:

    How to transform this into to a wordpress sidebar? Any help would be highly appreciated!!!

  22. NOMAD says:

    Thanks!!! It’s wonderfull! Great work!

  23. Imran says:

    I like it
    Thanks

  24. Clay says:

    Greetings,

    I am just learning php (been a CFer for years) and I have not been able to get this to work with blogger.com(blogspot). Has anyone else? It gets the entire feed post and scrolls. I only want a snippet of the feed for intro purposes.

    Thoughts?

    ~Clay

  25. Bob says:

    Hi,

    How do you call your own XML feed and input the images, I can call a normal text based Feed but whenever I try to add Images it fails ?

    Also what is the certificate all about in the cache folder ?

    Thanks

  26. thanks http://www.dfmoviez.co.cc/
    its really great. any one who want to link exchange contact me at aikajnabishahzada@gmail.com

  27. Heather says:

    This is great. Anyone know how to implement multiple instances on the same page? I’ve been working all day on this and can’t seem to get it right.

  28. Jim Wurster says:

    I was just looking for something like this as my friend asked me to update their website at http://www.sustainabledelco.org with some specific RSS feed. Since I use WordPress, I didn’t have to use all your code (did I goof there). Everything is there in the right sidebar at the top, but I don’t get any scrolling. If you can point me in the right direction to fix this, I would appreciate it.

    It’s probably a javascript conflict as I have a lot of scripts running.

    Thank you, jim

  29. Capnhairdo says:

    The chunky text issue—correctly noted as a ClearType problem in IE—can be fixed simply by removing the fade out. You could change this:

    { marginTop : ‘-’ + settings.list_item_height, opacity: ‘hide’ }

    to this:

    { marginTop : ‘-’ + settings.list_item_height}

    or even make it conditional upon the browser:

    $.browser.msie ? { marginTop : ‘-’ + settings.list_item_height } : { marginTop : ‘-’ + settings.list_item_height, opacity: ‘hide’ }

    There is another more inherent problem—whenever you set the delay lower than the speed, things go a bit haywire. The “delay” as implemented here is the interval on which the function runs itself again, regardless of whether the previous iteration is still going. The result is that you end up with list items on top of each other. Seems like a better approach would be to start the interval *after* the previous iteration has completed, so it can’t run into itself. Replacing the setInterval with this seems to fix it:

    window.scroller = function() {
    // Get the very first list item in the wrapped set.
    $this.children(‘li:first’)
    // Animate it
    .animate({
    marginTop : ‘-’ + settings.list_item_height, // Shift this first item upwards.
    opacity: ‘hide’ }, // Fade the li out.

    // Over the course of however long is
    // passed in. (settings.speed)
    settings.speed,

    // When complete, run a callback function.
    function() {

    // Get that first list item again.
    $this.children(‘li:first’)
    .appendTo($this) // Move it the very bottom of the ul.

    // Reset its margin top back to 0. Otherwise,
    // it will still contain the negative value that we set earlier.
    .css(‘marginTop’, 0)
    //.fadeIn(300); // Fade in back in.
    .show(); // Fade in back in.

    setTimeout( “scroller()”, settings.delay ); // call function again after interval
    }
    ); // end animate

    } // end scroller function

    scroller(); // initiate scoller

  30. mon says:

    Hi, I have tested it on IE7 and found that the contents are overflow. Can you please help to fix it.
    thankyou

  31. Amanda Gray says:

    I’m not sure why, but the screencast video is not showing up. When I right click on the video it has two options, “Movie Not Loaded” (Greyed out) and “About Adobe Flash Player 10.3.181.14…”

    I’m using Firefox 4.0.1. Any ideas on how I can watch the video?

  32. Pete says:

    Thanks! This is so simple and perfect!

Comment Page 2 of 2 1 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.