Speed up development with full-stack environments for every branch.

Learn More

Firebase Leaderboard Example [JavaScript]

Forked from Firebase Collaborative Drawing Example.

1782 Runs 4450 Views 1036 Copies


praful 60

published 4 years ago

  <title>Firebase Leaderboard Example</title>
  <script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://www.firebase.com/css/example.css">
<table id="leaderboardTable"></table>
<input type="text" id="nameInput" placeholder="Name">
<input type="text" id="scoreInput" placeholder="Score">

<div id="highestscore">
  Highest Score so Far: <span id="highestScoreDiv"></span>

<script type="text/javascript">

  // Build some firebase references.
  var rootRef = new Firebase('https://leaderboard-example.firebaseio-demo.com/');
  var scoreListRef = rootRef.child("scoreList");
  var highestScoreRef = rootRef.child("highestScore");

  // Keep a mapping of firebase locations to HTML elements, so we can move / remove elements as necessary.
  var htmlForPath = {};

  // Helper function that takes a new score snapshot and adds an appropriate row to our leaderboard table.
  function handleScoreAdded(scoreSnapshot, prevScoreName) {
    var newScoreRow = $("<tr/>");

    // Store a reference to the table row so we can get it again later.
    htmlForPath[scoreSnapshot.name()] = newScoreRow;

    // Insert the new score in the appropriate place in the table.
    if (prevScoreName === null) {
    else {
      var lowerScoreRow = htmlForPath[prevScoreName];

  // Helper function to handle a score object being removed; just removes the corresponding table row.
  function handleScoreRemoved(scoreSnapshot) {
    var removedScoreRow = htmlForPath[scoreSnapshot.name()];
    delete htmlForPath[scoreSnapshot.name()];

  // Create a view to only receive callbacks for the last LEADERBOARD_SIZE scores
  var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);

  // Add a callback to handle when a new score is added.
  scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
    handleScoreAdded(newScoreSnapshot, prevScoreName);

  // Add a callback to handle when a score is removed
  scoreListView.on('child_removed', function (oldScoreSnapshot) {

  // Add a callback to handle when a score changes or moves positions.
  var changedCallback = function (scoreSnapshot, prevScoreName) {
    handleScoreAdded(scoreSnapshot, prevScoreName);
  scoreListView.on('child_moved', changedCallback);
  scoreListView.on('child_changed', changedCallback);

  // When the user presses enter on scoreInput, add the score, and update the highest score.
  $("#scoreInput").keypress(function (e) {
    if (e.keyCode == 13) {
      var newScore = Number($("#scoreInput").val());
      var name = $("#nameInput").val();

      if (name.length === 0)

      var userScoreRef = scoreListRef.child(name);

      // Use setWithPriority to put the name / score in Firebase, and set the priority to be the score.
      userScoreRef.setWithPriority({ name:name, score:newScore }, newScore);

      // Track the highest score using a transaction.  A transaction guarantees that the code inside the block is
      // executed on the latest data from the server, so transactions should be used if you have multiple
      // clients writing to the same data and you want to avoid conflicting changes.
      highestScoreRef.transaction(function (currentHighestScore) {
        if (currentHighestScore === null || newScore > currentHighestScore) {
          // The return value of this function gets saved to the server as the new highest score.
          return newScore;
        // if we return with no arguments, it cancels the transaction.

  // Add a callback to the highest score in Firebase so we can update the GUI any time it changes.
  highestScoreRef.on('value', function (newHighestScore) {

Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).