Incorporating one-of-a-kind images into your JavaScript objects

Big shoutout to dmikester1 for sharing a LeaderBoard code that leverages Javascript data to organize players by their points.

The current implementation involves using the same image for each player's profile, but I have a vision to customize the pictures for each player individually...

You can see the code in action on JSFiddle

Here is the breakdown:

Javascript:

// array to store 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);

// sorting the array based on points
profiles.sort(function(a, b) { 
return b.points-a.points;
})

let profilesDiv = document.getElementsByClassName('profiles')[0];

let count = 1;
profiles.forEach(function(entry) {
    let img = document.createElement('img');
  img.className = "profilePic";
  img.src = "https://placeimg.com/50/50/people"; // replace with dynamic images
    let profile = document.createElement('div');
  profile.className = "profile";
  profile.innerHTML = "<div class='name'>"+ entry.name + "</div>";
  let points = document.createElement('span');
  points.className = "points";
  points.textContent = entry.points;
  profile.appendChild(points);
  profile.prepend(img);
  var span = document.createElement("span");
  span.textContent = count + '. ';
  span.className = "count";
  profile.prepend(span);
    profilesDiv.appendChild(profile);
  count++;

});

CSS:

.profile {
  border: 2px solid #555555;
  padding: 10px;
  margin: 5px;
  width: 30%;
  height: 50px;
  line-height: 50px;
}

.profile img, .profile .name {
  float: left;
  margin-right: 20px;
}

.profile .count {
  float: left;
  margin-right: 5px;
}

.profile img {
  border-radius: 50%;
  box-shadow: .6rem .5rem 1rem rgba(0, 0, 0, .5);
}

.points {
  float: right;
}

HTML:

<div class="profiles">

</div> 

Answer №1

To ensure each profile is complete, it is necessary to include an image property for every profile.

profile1.img= "https://randomuser.me/api/portraits/men/12.jpg"

Subsequently, the image must be retrieved and displayed for each individual profile.

img.src = entry.img;

Incorporating JavaScript:

// The array that will store all profile objects
let profiles = [];

let profile1 = {};
profile1.name = "Jim Bob";
profile1.points = 1500;
profile1.img= "https://randomuser.me/api/portraits/men/12.jpg";
profiles.push(profile1);

let profile2 = {};
profile2.name = "Jane Smith";
profile2.points = 1600;
profile2.img= "https://randomuser.me/api/portraits/women/22.jpg";
profiles.push(profile2);

// Additional profiles follow

// Sorting the array based on points
profiles.sort(function(a, b) { 
return b.points-a.points;
})

let profilesDiv = document.getElementsByClassName('profiles')[0];

let count = 1;
profiles.forEach(function(entry) {
    let img = document.createElement('img');
  img.className = "profilePic";
  img.src = entry.img;
    let profile = document.createElement('div');
  profile.className = "profile";
  profile.innerHTML = "<div class='name'>"+ entry.name + "</div>";
  let points = document.createElement('span');
  points.className = "points";
  points.textContent = entry.points;
  profile.appendChild(points);
  profile.prepend(img);
  var span = document.createElement("span");
  span.textContent = count + '. ';
  span.className = "count";
  profile.prepend(span);
    profilesDiv.appendChild(profile);
  count++;

});

CSS Styling Applied:

.profile {
  border: 2px solid #555555;
  padding: 10px;
  margin: 5px;
  width: 30%;
  height: 50px;
  line-height: 50px;
}

.profile img, .profile .name {
  float: left;
  margin-right: 20px;
  width: 50px;
  height: 50px;
}

// Additional CSS rules continue...

View the full code implementation here.

Answer №2

This section of code accomplishes the following task:

img.src = "https://placeimg.com/50/50/people";

It sets the image source for each player in the game.

If you aim to assign a unique profile picture to every player, you must include a src attribute in each player's profile.

let player1 = {};
player1.name = "Jim Bob";
player1.points = 1500;
player1.src = "Image source here";
players.push(player1);

Subsequently, within your forEach loop:

players.forEach(function(person) {
  let img = document.createElement('img');
  img.className = "profilePic";
  img.src = person.src;
  /....
 )}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while trying to render an item from a state array in React

I encountered an issue with retrieving state data within the render function. Everything seems to work fine and displays the array when I utilize console.log(items) However, attempting to access the first item from the array results in an error console. ...

The output produced by ASP.NET remains unaffected by JQuery or JavaScript interference

I am facing an issue with manipulating a dynamically generated directory tree in HTML format using JavaScript. I have a piece of code that generates the tree server-side in ASP.NET and then tries to add a '+' at the end of each list item using jQ ...

Error in GatsbyJS: Unable to retrieve data from property 'childImageFluid' due to undefined value

Currently tackling a Gatsby website, but running into an issue: "TypeError: Cannot read property 'childImageFluid' of undefined" Here's the code snippet from my Project.js file: import React from "react" import PropTypes from &quo ...

How can I eliminate unwanted zombie events in Vue JS?

How do you get rid of a zombie event? When navigating back and forth, the events run multiple times. MainApp.vue <template> <input type="button" @click.prevent="handleClick()" value="Click Me"> </template> <script> export defa ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

What are the best practices for incorporating keywords into HTML code for SEO purposes?

Even though this topic is borderline related to programming questions, I believe it's still relevant here. After all, only those of us who are actually coding for a website would be considering this aspect. Lately, I've been delving deeper into ...

Top method for tracking changes in numerous textboxes

I'm currently working on a form that is organized into tabs using jQuery. Each tab contains different elements of the form related to a specific section, with a save button at the bottom of each tab. I want to implement a feature where a warning icon ...

State update failing to modify arrays

Shown below is an array that contains boolean values: const [state, setState] = React.useState({ [`${"checkedA"+index}`]: false, [`${"checkedB"+index}`]: false, [`${"checkedC"+index}`]: false, [`${"checkedD"+index}`]: false, }); ...

What are some ways I can ensure my webpage remains consistent and user-friendly when scrolling, rather than appearing distorted and jumbled?

Is there a way to automatically scroll my page when the window is at a small height, instead of adjusting it to the height by squeezing it? I've tried using overflow in different ways, but haven't been successful in getting the entire page to scr ...

Is there a way to undo the changes made by the following execution using Javascript?

Similar Question: How can I delete a cookie using JavaScript? javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com”); To undo the action perfor ...

I need to retrieve data from two different databases. What is the best way to combine the code into a single function?

I am working on fetching data from 2 database sources and combining them to send the merged data to result.html function showResult(req, res){ var n = req.query.query mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE ...

What is the reason behind React re-rendering child components despite passing props that have been memoized with useMemo?

While exploring this topic, I stumbled upon an answer that seems relevant: When does React re-render child component? However, my inquiry delves into a more intricate question. Why does React typically re-render child components when utilizing the useMemo ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

Hide the Modal Content using JavaScript initially, and only reveal it once the Onclick Button is activated. Upon clicking the button, the Modal should then be displayed to

While trying to complete this assignment, I initially attempted to search for JavaScript code that would work. Unfortunately, my first submission resulted in messing up the bootstrap code provided by the professors. They specifically requested us to use Ja ...

Firefox version 78.0.1's Responsive Design Mode fails to provide accurate window.innerWidth values after screen orientation change

Could this be a bug specific to Firefox, or have I made an error somewhere? When testing in Chrome or on an actual device like Android, everything works fine. It appears to be an issue only when using Firefox's Responsive Design Mode. Below is the c ...

Developing an animated feature that displays a dynamic count up to the current size of the browser window

I have a script that's able to determine the height and width of my browser window. However, I am facing a challenge in creating a way for these dimensions to count up from zero to their current values upon loading. The desired functionality would be ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Making the text gradually disappear at the bottom of a section using a see-through overlay, while ensuring the height remains within the boundaries of the section even

Trying to achieve a sleek fade-out effect at the end of a text section for a 'read more' indicator. I've been studying various tutorials, including this, and my current code is as follows: html <section> <p>Lorem ipsum dol ...

What is preventing SVG textPath from displaying properly? [Empty output in devtools]

I found this interesting code snippet on Mozilla and decided to incorporate it into a Vue component. <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path id="MyPath" fill="none" stroke="red" d="M10,90 Q90,90 90,45 Q90,10 ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...