Dynamic Leaderboard

So you want to create a dynamic leaderboard that changes on the fly using jQuery? Well do ya?

Here’s the scenario: you have some cool (to you at least) data that you want to put up on a webpage/kiosk/touchscreen/smartphone that animates beautifully in real time to update the results.

Here’s an example of what I’m talking about:


    You’ll notice that when a record updates, it will re-order the list depending on where a change has happened, in real time, without you having to do anything. This is ace for games, ops screens and anything else where you want to show off the timely prescience of your data which has a rating or score driving the reason behind its presentation.

    All I’m going to talk about here is the front end – specifically how we can create a simple web page that will poll a server for any changes in the data. It’s up to you how you create your back end. However, the ajax poll expects a response in JSON – see step 2 below about what this needs to look like.

    Step 1: the leaderboard

    <ul id="leaderboard"></ul>

    It’s an empty unordered list that will get populated by our jQuery ajax method in step 2…

    Step 2: the poll

    When the page loads, it will fire off poll() which will recursively call itself every 3 seconds.

    The first thing it does is request the most up to date data from your server in a JSON format. For the sake of this example, it needs to look like this:

    [ { "facebook_id" : "606970183",
    "id" : "3",
    "score" : "269",
    "username" : "Ant"
    },
    { "facebook_id" : "627180753",
    "id" : "4",
    "score" : "268",
    "username" : "Stuart"
    },
    etc...
    ]

    The poll method iterates through the JSON data. If an li already exists with a reference to the id in the data it contains it will update the li with the new count. If the li doesn’t exist with the id of the record you’re bringing back (probably because it’s a new entry in the results), it will append to the unordered list you have.

    	function poll() {
    		$.ajax({
    			url: '/ajax/sort-leaderboard', // needs to return a JSON array of items having the following properties: id, score, facebook_id, username
    			dataType: 'json',
    			success: function(o) {
    				for(i=0;i<o.length;i++) {
    					if ($('#user-'+o[i].id).length == 0) {
    						// this id doesn't exist, so add it to our list.
    						$("#leaderboard").append('<li><h1 style="display:inline" id="user-' + o[i].id + '">' + o[i].score + '</h1> <img style="height:50px" src="http://graph.facebook.com/' + o[i].facebook_id + '/picture"/> ' + o[i].username + '</li>');
    					} else {
    						// this id does exist, so update 'score' count in the h1 tag in the list item.
    						$('#user-'+o[i].id).html(o[i].score);
    					}
    				}
    				sort();
    			},
    		});	
    
    		// play it again, sam
    		t=setTimeout("poll()",3000);
    	}

    Step 3: the sorting

    After the list gets updates the poll() method calls the sort() method.

    I wasn’t clever enough to figure this out, so I nicked the excellent animated sorting example from http://tinysort.sjeiti.com/.

    It will sort the results that have been updated in step 2 in a groovy way. Tinysort doesn’t animate itself, but it will sort your data and then use regular jQuery to animate it. The key things to remember is that you want to target the contents of the h1 which contains the score itself, so the first parameter for tsort is ’h1:eq(0)’ and the dude with the highest score goes on top, so the second parameter is setting the option of your sort order, like this: {order:’desc’}.

    	function sort() {
    		var $Ul = $('ul#leaderboard');
    		$Ul.css({position:'relative',height:$Ul.height(),display:'block'});
    		var iLnH;
    		var $Li = $('ul#leaderboard>li');
    		$Li.each(function(i,el){
    			var iY = $(el).position().top;
    			$.data(el,'h',iY);
    			if (i===1) iLnH = iY;
    		});
    		$Li.tsort('h1:eq(0)',{order:'desc'}).each(function(i,el){
    			var $El = $(el);
    			var iFr = $.data(el,'h');
    			var iTo = i*iLnH;
    			$El.css({position:'absolute',top:iFr}).animate({top:iTo},500);
    		});
    	}

    Once it starts animating, the poll() method creates a timeout to call itself again so it can do this all over again.

    As I mentioned, the back end is up to you, but here’s how it’s done for this example using the Zend Framework with php:

    	$sql = "SELECT id,score,username,facebook_id FROM leaderboard_users ORDER BY score DESC";                
    	$results = $this->db->query($sql)->fetchAll();                
    	$table = new Zend_Db_Table("leaderboard_users");        
    	$table->update(array("score"=>$results[count($results)-1]['score'] + 2),'id='.$results[count($results)-1]['id']);                            
    	echo Zend_Json::encode($results);

    You can download the html and jQuery code for this here.

    Go forth and dynamically leaderboard things.

    No Comments

    Sorry, the comment form is closed at this time.

    Isometric Projection with JavaScript in HTML5 vs Flash and Actionscript

    Recently I decided to build part of a game that used an isometric projection for displaying the game board using HTML5.
    Dirty plagiarist that I am, I found an excellent (albeit very old) tutorial by Danko Kozar for doing this. However it was written in Actionscript. No bother – I just modified the code to work in HTML5. This meant I could more or less ignore the theory of how isometric projection works and just get down to the business of doing it. Porting the code was easy. As it says in the tutorial:

    These tutorials can be used for programming an isometric game in many programming languages not just in Flash. They are more about game programming than about Flash programming.

    Here’s the swf from Danko’s tutorial:
    Details »

    Dynamic Leaderboard

    So you want to create a dynamic leaderboard that changes on the fly using jQuery? Well do ya?

    Here’s the scenario: you have some cool (to you at least) data that you want to put up on a webpage/kiosk/touchscreen/smartphone that animates beautifully in real time to update the results.

    Details »

    Handy Linux Shortcuts and How To’s

    Here’s some linux tricks I use in my line of work. I find them useful, you may not. You decide.
    Details »

    Friend Photomosaics


    Turn your Facebook profile picture into a photomosaic made up of your friends profile pictures.

    Details »

    PHP Chart Class

    Create line or bar charts and graphs within php. They can be output directly or image files created.

    Details »

    Drawing Gallery

    Create your own drawing

    Details »

    Create Flash Drawing

    A collection of many spontaneous drawings generated with Flash

    Over a thousand random drawings created since 2003.

    Details »

    Font List


    Details »

    PHP Thumbnail Script

    A script for converting images to different sizes inline, with support for server caching.

    Details »

    Flash Chess

    Chess program designed to learn from player interaction. Made with flash and PHP server technology, the finished version will (in theory) be able to beat all players that aren’t as good as players that have played the system often.

    Details »