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

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Colin McFadden

    Nice tutorial, mate!

  • http://www.eraxa.com Sirwan

    this will come in handy

  • http://www.anthonyjamesbruno.com Anthony James Bruno

    Hey how about a demo?

  • Meshach

    Awesome work Jeffrey!!

  • http://eyoosuf.blogspot.com/ Yoosuf

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

  • SX

    Really sweet. Thanks man.

  • http://www.rizqtech.net rizq

    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

    • http://www.jeff-way.com Jeffrey Way
      Author

      Sure. But the code will need to be modified.

  • Logie

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

    It’s really nice :]

    • http://delicon.mk Daniel

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

      • http://wpdots.net Patrascu Vlad

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

  • http://www.brenelz.com/blog Brenelz

    Nice tutorial Jeffery… they all are :)

  • http://blog.insicdesigns.com insic

    this is cool. thanks for sharing

  • http://www.brandensilva.com Branden Silva

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

  • http://www.freshclickmedia.com Shane

    Nice post. Thanks.

  • Ville

    Yeah, a demo would be nice.

  • Mexx

    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 ;-)

  • http://www.patternhead.com Patternhead

    Nice work

  • http://abdusfauzi.com abdusfauzi

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

  • Pingback: BLOG { jörg steinhauer } » Gods of GFX #2

  • http://www.websheffield.com Ed Baxter (Web Sheffield)

    Great stuff as always Jeff :D

  • erenHun

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

  • http://www.jeffadams.co.uk Jeff

    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.

  • Jem

    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.

  • http://www.apostropheart.com/ Mike

    Cool RSS Scroller.

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

  • Pingback: How to Build a Super Duper News Scroller | DeanWorks

  • http://www.geekstore.ru UglyToys

    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.

  • http://www.iammikesmith.com Mike Smith

    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.

  • http://satula.co.cc Taylor Satula

    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

  • http://satula.co.cc Taylor Satula

    P.S What happened to the demo???

  • http://www.sanjoseca.gov/prns/newsScroller/ Ricardo

    great tutorial

  • SX

    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.

  • http://www.benniemosher.com Bennie Mosher

    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.

  • Meshach

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

  • lenin

    This is really nice. Thank you.

  • Niklas

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

  • pallu

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

  • http://www.menacestudio.com Dennis

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

  • Hassan

    @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

  • Pingback: NETTUTS.com: How to Build a Super Duper News Scroller : Dragonfly Networks

  • Pingback: Daily Digest for 2009-03-20 | This is Chris

  • Dnyanesh

    @Hassan @ Paul

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

  • http://www.mutantweb.com/ Roosevelt P.

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

  • Eduardo

    simply great ;)

  • Milena

    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!

  • Pingback: vivanno.com::aggregator » Archive » Construire un super nouveau scroll

  • Pingback: Construire un super nouveau scroll | traffic-internet.net

  • http://taimurian.com Taimur Aziz

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

  • Pingback: ForTheLose.org - FTL Weekly Review - Vol. 7

  • http://www.exoflux.co.uk Luke

    What program was you using to code with?

  • A Stephens

    Great Tutorial!

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

    • http://nbm.com.au Kyle Stevenson

      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!

      • LuK

        thx kyle,

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

  • Pingback: NETTUTS.com: How to Build a Super Duper News Scroller | pcsourcenetwork.com

  • Tanax

    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!