Search code examples
javascripthtmlcssleaderboard

Creating a dynamic LeaderBoard with profile pictures


I want to find a way to create a leaderboard like one below that uses variables to hold Users Points on Javascript in order to respond to changes to those points with changing users Ranks...

Here is what I'm trying to achieve:

Here is the picture

I just want to manually fill in User's Points Data using only Javascript Variables... all the Data would come from a javascript array.

Something like :

   user_1 = Nilesh S;
   user_2 = Shristi_S; 

   user_1 points = 1710;
   user_2 points = 1710;

   etc...

Obviously, If I change Nilesh S (user_1) points to 1000 then Nilesh S rank will be 10th...

What I achieved for now is just creating those circle profile pictures :)

Here are the codes:

Javascript:

var img = document.createElement("IMG");
  img.setAttribute("src", "img_pulpit.jpg");
  img.setAttribute("width", "300");
  img.setAttribute("height", "300");
  img.setAttribute("alt", "The Pulpit Rock");
  document.body.appendChild(img);

HTML:

<div id="IMG">
<script src="Script.js"></script>
<link rel="stylesheet" type="text/css" href="Style.css">
  [1]: https://i.sstatic.net/zXm4N.png

CSS:

img {
      background: #2f293d;

   border: 1px solid #2f293d;
   padding: 6px;
   border-radius: 50%;
   box-shadow: .6rem .5rem 1rem rgba(0, 0, 0, .5);

}

Any Solution will be greatly appreciated.


Solution

  • Here is a quick and dirty way to create some dummy data in an objects array, sort it, and add it to the page.

    // this is the array that will hold all the profile objects
    let profiles = [];
    
    let profile1 = {};
    profile1.name = "Jim Bob";
    profile1.points = 1500;
    profiles.push(profile1);
    
    let profile2 = {};
    profile2.name = "Jane Smith";
    profile2.points = 1600;
    profiles.push(profile2);
    
    let profile3 = {};
    profile3.name = "Mike Jones";
    profile3.points = 400;
    profiles.push(profile3);
    
    let profile4 = {};
    profile4.name = "Sally Peterson";
    profile4.points = 1900;
    profiles.push(profile4);
    
    // sort the array by points
    // b - a will make highest first, swap them so a - b to make lowest first
    profiles.sort(function(a, b) { 
    return b.points-a.points;
    })
    
    let profilesDiv = document.getElementsByClassName('profiles')[0];
    
    profiles.forEach(function(entry) {
    	let profile = document.createElement('div');
        profile.className = "profile";
        profile.textContent = entry.name + " -- " + entry.points;
    	profilesDiv.appendChild(profile);
    });
    .profile {
      border: 2px solid #222222;
      padding: 5px;
      margin: 5px;
      width: 50%;
    }
    <div class="profiles">
    
    </div>