How to Display Justin Bieber Tweets with Asynchronous Recursion
videos

How to Display Justin Bieber Tweets with Asynchronous Recursion

Tutorial Details
  • Topic: Justin Bieber News (or JavaScript)
  • Estimated Difficulty: Intermediate
  • Format: 20 Minute Screencast

Bottom line: Justin Bieber = traffic. I fully intend to use this to my advantage, and none of you can do anything about it. The purpose of today’s video tutorial is to demonstrate how to use a scary set of words, “asynchronous recursion” to continuously display updated tweets about the great Biebster. And then finally, we’ll hijack these tweets to make them look as if they’re referring to Nettuts+ instead.


The Full Source

<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<title>The Biebster</title>
</head>
<body>

	<h2> Latest Biebster Tweets </h2>
	<ul id="tweets"> </ul>

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

	<script>

	(function() {
		var UpdatePanel = {
			init : function(options) {
				this.options = $.extend({
					interval : 5000,
					number : 3,
					hijackTweet : false
				}, options);
				
				this.updater();
			},

			updater : function() {
				(function updateBox() {
					this.timer = setTimeout(function() {
						updateIt();
						updateBox();
					}, UpdatePanel.options.interval);
				})();

				// get the ball rolling
				updateIt();

				function updateIt() {
					$.ajax({
						type : 'GET',
						url : UpdatePanel.options.url,
						dataType : 'jsonp',

						error : function() {},

						success : function(results) {
							var theTweets = '',
								 elem = UpdatePanel.options.elem.empty();

							$.each(results.results, function(index, tweet) {
								if ( UpdatePanel.options.hijackTweet ) {
									tweet.text = tweet.text.replace(/(Justin )?Bieber/ig, 'Nettuts'); 
								}

								if ( index === UpdatePanel.options.number ) {
									return false;
								}
								else {
									theTweets += '<li>' + tweet.text + '</li>';
								}
							});
							elem.append(theTweets);
						}
					});
				}
			},

			clearUpdater : function() {
				clearTimeout(this.timer);
			}
		};
		window.UpdatePanel = UpdatePanel;
	})();

	UpdatePanel.init({
		interval : 5000,
		number : 5,
		url : "http://search.twitter.com/search.json?q=bieber",
		elem : $('#tweets'),
		hijackTweet : true
	});
	</script>
</body>

</html>

Conclusion

Thanks for watching; I hope you enjoyed it! Stay tuned to Nettuts+ for more news and gossip on Justin Bieber!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://smallbitsofcode.com Boba

    It’s funny how Justin Bieber provokes violence and hatred in comments.

  • http://brianegan.com Brian Egan

    Another way to make the code even just a little shorter, for those who may be interested, is to utilize jQuery’s “jsonp” dataType. For example, you could remove this line:

    this.options.url += ‘&callback=?’;

    And change:

    $.ajax({
    type : ‘GET’,
    url : UpdatePanel.options.url,
    dataType : ‘json’,

    • http://brianegan.com Brian Egan

      Ack, accidental submission! Change the previously listed ajax to:

      And change:

      $.ajax({
      type : ‘GET’,
      url : UpdatePanel.options.url,
      dataType : ‘jsonp’, // jsonp instead of json

      The dataType: 'jsonp' will actually ‘add an extra “?callback=?” to the end of your URL to specify the callback.’ (from the jQuery API docs).

      I’m sure you were just being explicit about it for new-comers, but for those who want to be as lazy as I like to be, not a bad alternative.

      Cheers,
      Brian

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

        Ahh – good tip, Brian. Thanks!

      • Ihab Khattab

        Nice tip

        First time to know

  • Ryan

    Don’t listen to all the stupid immature commenter’s who can’t take a joke Jeff; This was yet another quality tutorial.

  • Tim

    When Justin sees this, she’ll be so pissed

  • http://sitebase.be Sitebase

    Just what I needed for my new Justin Bieber fan site project.
    Thanks Jeffrey!

  • Overkil

    Great tutorial, Jeff. I’m not sure how Bieber tweets are going to attract viewers, but eh, still amusing. I did, however, notice one small error in the above code, at line 52:

    var elem = UpdatePanel.options.elem.empty();
    //Should be
    var elem = UpdatePanel.options.elem;
    elem.empty();

    The code is right in the screencast, it just must have happened during repasting. Anyway, great concept with the tweets. I think it would great if you dissected jQuery’s ‘ajax’ method next (just sayin’ :) ).

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

      Actually, I changed that after the fact. It saves one line of code. :)

  • http://www.stav.co Mathias M. Stav

    Great :P Love it!
    Did it get you more traffic to use Bieber in this tutorial?

  • Simon

    Wading through all the idiots whinging about Justin Bieber, there are very few people actually commenting on the code.

    I would say that within an object such as UpdatePanel you should avoid referring to itself by variable name and instead use the this keyword.

    Makes it easier to update and maintain.

    You can easily set the context of the object methods with $.proxy, call or apply. Also the ajax method even has a context property to allow easy binding of this within it’s callback functions.

  • Liam

    That background photo disturbed my will to watch the whole video, so i will figure it out myself how the code works great :)
    Please at least don’t put it on a background.

    emmm What about Lady GAGA initiative to drive more traffic in ?!

  • w1sh

    I lol’d

  • http://coley.co Stephen Coley

    Changed the code so the new tweets load from the top and neatly scrolls down.

    Check it out: http://coley.co/demo/bieber.html

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

      Looks good, Stephen!

  • http://onelazydude.com Nikunj Chapagain

    To understand the code aspect of this tutorial, I think I must purchase a membedrship.

  • http://philwebservices.i.ph/ John Paul

    Nice tutorial

  • http://www.myastrodata.com/ Vladimir

    Useful tutorial, as usual, thank you!

    I’ve been changing slightly the base code, here is the the result app: http://www.myastrodata.com/dev/tweets.html

  • http://www.shaherhan.com cloud

    awesome, I need all the traffic I can get

  • http://matteoinvernizzi.altervista.org/projects/marquee.html do u remembrer old good websites?

    Probably Justin Bieber wasn’t already born when i’m started to navigate on internet :))

  • Zachary

    What happened to the video? Copyright infringement?

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

      Just checked; it’s still there.

  • http://www.giulianoliker.com Giuliano

    As always brilliant job Jeffrey, I really enjoyed it.

    I’m a little bit surprised with so many Bieber comments. Do you guys get a joke? What’s the problem with you: No sense of humor, no girlfriend or both?

  • Gregi

    Thanx Jeffrey, i think i’ll finally learn ajax thanks to this tutorial,

    Peace

  • http://shawntysco.com Shawn Tysco

    Here is a quick addition to the code – able to search results.

    http://tweetingwithtwitter.com/home.php

  • PDesign

    You are pulling all tweets from twitter and just show 3 of them?
    so why don’t you just pull only 3 latest tweets?

    like

    http://search.twitter.com/search.json?q=bieber&rpp=3

    hope i am not wrong (:

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

      No, you’re right. The only reason is to give the downloaders the option of setting how many to display. :) But sure, that’s a small update that could made to the init call.

  • noname

    Dear God,

    Please, send Eazy-E back to us and we will bring you Justin Beaver.

    Signed – The Whole World.

  • http://www.idesigncrap.wordpress.com Antor

    Maybe I should do this on my blog. LOL!! Id think Nettuts has enough traffic already. Nice tutorial though.

  • http://fabryz.com Fabryz

    Nice tutorial Jeffrey, i’ve just added a simple form to change the parameters for the query, and styled a bit =)

    http://labs.fabryz.com/twitter-asynch-recursion/

  • http://www.isuez.com/ isuez

    very nice thanks….

  • bieberftl

    it’s sad how marketing works nowadays. It’s changed so much that pathetic, talentless hacks like Bieber can succeed. As long as corporate fatheads make money they could care less. I refuse to promote anything of the sort on my own sites.

    • tigerlabs

      lol

  • Brannon

    Are you going to write a book on JavaScript? I think I’d buy a copy!

  • Nobody

    Who the heck is Justin Beinber?

    • SKyintheSeA

      go to youtube.com and type that name, then thumb up when you see something like ” if you’re here to see the page view, thumb up”

  • iamjem

    I could be wrong, but it looks like there’s one error in your code.

    The UpdatePanel.updater method has the anonymous self executing function at the beginning which starts like:

    this.timer = …

    “this” will reference the window, and not the UpdatePanel object. So your clearTimeout call later, if used, wouldn’t do anything.

    Otherwise nice tutorial.

  • http://www.twostepmedia.co.uk Ben Howdle

    Hi, this is a great tutorial and very topical, love the Twitter integration. Have a read and download of this and see what you think: http://blog.twostepmedia.co.uk/live-twitter-trends-on-a-website/

    Thanks Nettuts, keep writing!

  • http://www.planetnana.co.il/punka1/justin-follow.htm Tirearredlota

    sweet, interesting blog post! i find out so how to do justin bieber follow u of twitter
    its right here
    http://www.planetnana.co.il/punka1/justin-follow.htm

  • http://www.benedikt-wolters.de/blog Benedikt

    This is so awesome. Finally i can offer my clients full Bieber-Integration!

  • Alberto

    muy bueno amigo gracias