How to Build a Simple News Scroller

How to Build a Super Duper News Scroller

Mar 19th in Screencasts by Jeffrey Way

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.

PG

Author: Jeffrey Way

Hi, I'm Jeff. I'm the editor of Nettuts+, and the Site Manager of Theme Forest. I spend too much time in front of the computer and find myself telling my fiance', "We'll go in 5 minutes!" far too often. I just can't go out to dinner while I'm still producing FireBug errors...drives me crazy. During my free time, I sporadically write articles for my own personal blog. If it will keep you in the good graces of the church, follow us on Twitter.

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


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Colin McFadden March 19th

    Nice tutorial, mate!

    ( Reply )
  2. PG

    Sirwan March 19th

    this will come in handy

    ( Reply )
  3. PG

    Anthony James Bruno March 19th

    Hey how about a demo?

    ( Reply )
  4. PG

    Meshach March 19th

    Awesome work Jeffrey!!

    ( Reply )
  5. PG

    Yoosuf March 19th

    nice tut, BTW what is that coming in Yellow color while you are hovering?

    ( Reply )
  6. PG

    SX March 19th

    Really sweet. Thanks man.

    ( Reply )
  7. PG

    rizq March 19th

    Hi..Jeff,
    Any possible to include in wordpress ?

    i was used simplie plugin for wordpress, and then like this

    Fatal error: Cannot redeclare class simplepie in /home/user/public_html/simplepie.inc on line 386

    ( Reply )
    1. PG

      Jeffrey Way March 19th

      Sure. But the code will need to be modified.

      ( Reply )
  8. PG

    Logie March 19th

    What text editor do you use mate and is that the default theme that comes with it?

    It’s really nice :]

    ( Reply )
    1. PG

      Daniel March 20th

      It’s E – TextEditor and that it’s not the default theme.

      ( Reply )
      1. PG

        Patrascu Vlad March 20th

        but it`s included so you can easily change it.

  9. PG

    Brenelz March 19th

    Nice tutorial Jeffery… they all are :)

    ( Reply )
  10. PG

    insic March 19th

    this is cool. thanks for sharing

    ( Reply )
  11. PG

    Branden Silva March 20th

    Simple code for a simple effect. I like it. Nice work Jeffrey.

    ( Reply )
  12. PG

    Shane March 20th

    Nice post. Thanks.

    ( Reply )
  13. PG

    Ville March 20th

    Yeah, a demo would be nice.

    ( Reply )
  14. PG

    Mexx March 20th

    nice tut. you killed two birds with one stone. people are getting a new great tut and some of them will hopefully use the same rss-feed as you did. these guys are backlinking to net.tutsplus.com and promoting for it ;-)

    ( Reply )
  15. PG

    Patternhead March 20th

    Nice work

    ( Reply )
  16. PG

    abdusfauzi March 20th

    i think, a demo would come in handy. here, video streaming is very slow. T_T

    ( Reply )
  17. Great stuff as always Jeff :D

    ( Reply )
  18. PG

    erenHun March 20th

    You are perfect . Thanks for sharing this will be very useful for my upcoming projects

    ( Reply )
  19. PG

    Jeff March 20th

    Where is the demo or are you just teasing us with your technical know-how?

    20 mins though – that is impressive I have to say. I might put this on my own site or some templates for Themeforrest – saying thta there is a few of these knocking around.

    ( Reply )
  20. PG

    Jem March 20th

    nice tutorial.

    nice to see other people using e-texteditor. its not quite as useful in some of the bundles as it is in others… i’ve found it most useful in higher level programming languages than working with markup like HTML.

    ( Reply )
  21. PG

    Mike March 20th

    Cool RSS Scroller.

    Isn’t Simple Pie overkill for something like this though? I think SimpleXML would be a better option.

    ( Reply )
  22. PG

    UglyToys March 20th

    Dude, don’t stop with SimplePie and RSS tuts. There are awesome.

    For example, try parse Google shared items feed, like this, and add results like a posts in personal blog on wordpress or smthg same.

    And thanks for tut.

    ( Reply )
  23. PG

    Mike Smith March 20th

    I’d love to see more jQuery tutorials. The jQuery part of this tutorial had me glued. I’m hooked :) Awesome tutorial – I’ll be using this in a few new projects.

    ( Reply )
  24. PG

    Taylor Satula March 20th

    Huh, cool this is a really good idea. I think someone said it already but SimpleXML would be better. kinda overkill but not too much

    ( Reply )
  25. PG

    Taylor Satula March 20th

    P.S What happened to the demo???

    ( Reply )
  26. PG

    Ricardo March 20th

    great tutorial

    ( Reply )
  27. PG

    SX March 20th

    I modified this code, wrote a small function using PHP simpleXML to parse the data,got rid of simplepie,and it works just as good. The simpleXML functions page is only 3kb. I also added support for the Flickr RSS, so now I can get custom Flickr searches displayed. The jQuery code made it all work nicely. Thanks Jeffrey for your help.

    ( Reply )
  28. PG

    Bennie Mosher March 20th

    I am having problems getting this to work on my companies site. I have copied just about everything that you are doing, but it isn’t working. I am generating the content using WordPress functions, instead of SimplePie, but that shouldn’t make the jQuery stop working. The only thing that isn’t working is that it doesn’t scroll up. Can someone help me please?

    The site can be found here:

    http://rmwebsite.com/rosemontmedia/

    It is the Rosemont Review box.

    ( Reply )
  29. PG

    Meshach March 20th

    Jeffrey are you using the Espresso theme on e-text-editor?

    ( Reply )
  30. PG

    lenin March 20th

    This is really nice. Thank you.

    ( Reply )
  31. PG

    Niklas March 20th

    Indeed a new tutorial Jeffrey. Simple yet useful. Great work.

    ( Reply )
  32. PG

    pallu March 20th

    What is that program that lets you write “jquery” and all the “<script …” appears?

    ( Reply )
  33. PG

    Dennis March 20th

    Any way to do add Simple Pie to an ASP.NET site?

    ( Reply )
  34. PG

    Hassan March 20th

    @Pallu,

    That software is called the Text Expander. You can watch Jeff’s Tut on that as well.

    It says ” How i code twice as fast as you “.

    Go ahead and watch that and you will learn how to do so.

    Thanks

    -Hassan

    ( Reply )
  35. PG

    Dnyanesh March 21st

    @Hassan @ Paul

    It is called as ‘Texter’. Get it on Lifehacker.com

    ( Reply )
  36. PG

    Roosevelt P. March 21st

    I loved this tutorial, thank you for the great explanations :) .

    ( Reply )
  37. PG

    Eduardo March 21st

    simply great ;)

    ( Reply )
  38. PG

    Milena March 21st

    This tutorial is great! Being a newbie and all, I was really happy to get it to work. NOW ~ after seeing how cool it would be to implement something like this on my sites, I tried to find tuts on actually making rss-feeds and guess what, they all suck. Would it be too much to ask that you go through the basics of putting an rss feed together?

    Thanks!

    ( Reply )
  39. PG

    Taimur Aziz March 21st

    Thank you so so much .. I really wanted something like this .. please add more news scrolling tutorials ( jquery of course )

    ( Reply )
  40. PG

    Luke March 22nd

    What program was you using to code with?

    ( Reply )
  41. PG

    A Stephens March 22nd

    Great Tutorial!

    Does anyone have a suggestion for the best way to pause the animation on hover?

    ( Reply )
    1. PG

      Kyle Stevenson August 16th

      I’ve modified the original code to pause the News Scroller when you hover over it. You can find the code here:

      http://snipt.org/lmph

      Thanks Jeffrey, great little plugin you have there!

      ( Reply )
      1. PG

        LuK August 18th

        thx kyle,

        I should have read all the comments before posting mine about how to pause this nice script =)…

  42. PG

    Tanax March 23rd

    This is great!
    Thanks for this!

    One question though.
    How come if you pull 15 results with the simplepie, and you foreach those results, only 3 are displayed? I really didn’t understand that. Other than that, this was great!

    ( Reply )
  43. PG

    Deoxys March 24th

    No Demo?

    ( Reply )
    1. PG

      lawrence77 March 24th

      :(

      ( Reply )
  44. PG

    Dileep K Sharma March 25th

    Is it possible for you to include a Demo for this? It would greatly help.

    ( Reply )
  45. PG

    Kevin March 26th

    It’s not hard to create your own:

    http://work.kevinleary.net/newsScroller/

    Download, unzip, upload and open.

    ( Reply )
  46. PG

    ozge March 29th

    great tut indeed.

    I have a question?

    How did you manage to display only the images in a RSS feed? If you look at the RSS feed of NETTUTS, you will notice that there is only single image for each post.

    Thanks

    ( Reply )
  47. PG

    Al March 29th

    I edited this codes jquery,css and removed simple pie and used php simplexml. I used it for this news site.

    http://www.gsun.info

    ( Reply )
  48. PG

    Mauro De Giorgi April 4th

    Cool! i like it very much, thank you :)

    ( Reply )
  49. PG

    Lalor McMahon April 14th

    Nice work – very simple application of a very useful feature

    ( Reply )
  50. PG

    coda April 16th

    Demo or it didn’t happen

    ( Reply )
  51. PG

    xxx May 6th

    Hi everyone,

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

    later ….

    ( Reply )
  52. PG

    Matthias May 12th

    Thank you, that’s perfect !

    ( Reply )
  53. PG

    Abubaker June 13th

    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…

    ( Reply )
  54. PG

    Anders June 22nd

    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?

    ( Reply )
  55. PG

    Anders June 23rd

    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

    ( Reply )
  56. PG

    LuK July 29th

    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!

    ( Reply )
  57. PG

    Sangam Uprety August 6th

    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!

    ( Reply )
  58. PG

    Sangam Uprety August 6th

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

    ( Reply )
    1. PG

      Rob August 6th

      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)

      ( Reply )
  59. PG

    Keith N August 25th

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

    ( Reply )
  60. PG

    Fernando September 15th

    New blog

    ( Reply )
  61. PG

    Puneet Pandey September 18th

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

    ( Reply )
  62. PG

    Puneet Pandey September 19th

    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

    ( Reply )
  63. PG

    Mr.Mark September 24th

    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.

    ( Reply )
  64. PG

    Rhett Forbes September 25th

    works like a charm

    Thanks
    Rhett

    ( Reply )
  65. PG

    Mr.Mark October 13th

    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)

    ( Reply )
  66. PG

    rob October 16th

    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.

    ( Reply )
  67. PG

    singapore cheap October 21st

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

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    October 21st