What is the best way to dynamically assign classes to a single <li> element in Meteor when an event occurs?

I'm a newcomer to the meteor framework and I'm attempting to create a project where clicking on the name within a <li> element changes the background color to yellow. When another <li> element is clicked, the previous one should revert to its original color and the newly clicked <li> should turn yellow.

I attempted to achieve this by adding a .selected class using the unique id from MongoDB. However, my implementation, which compares the ids using an if statement, doesn't seem to be working as expected.

Here is the code snippet:

body.html:

<body>
    <h1>Leaderboard</h1>
    {{> leaderboard}}
</body>

<template name="leaderboard">
<ul>
    {{#each player}}
        <li class="player {{selectedClass}}">{{name}}: {{score}}</li>
    {{/each}}
</ul>
</template>

body.js:

 import {Template} from 'meteor/templating';
 import './body.html';
 import {PlayersList} from '../api/players.js';

    Template.leaderboard.helpers({
            'player': function(){
                return PlayersList.find();
            },
            'selectedClass': function(){
                var playerId = this._id;
                var selectedPlayer = Session.get('selectedPlayer');
                if(playerId == selectedPlayer){
                    return "selected"
                }
            }  
        });

    Template.leaderboard.events({
        'click .player': function(){
            var playerId = this._id;
            Session.set('selectedPlayer', playerId);
        }
    });

main.css

.selected{
    background-color: yellow;
}

Here is a screenshot of the output:

https://i.sstatic.net/vsrCD.png

Answer №1

If you're looking to improve your Template, I have some suggestions for you. Below are the changes I recommend, along with explanations.

leaderboard.html

(please note that we are now passing _id to the helper)

<template name="leaderboard">
  <ul>
    {{#each player}}
      <li class="player {{selectedClass _id}}">{{name}}: {{score}}</li>
    {{/each}}
  </ul>
</template>

leaderboard.js

import {Template} from 'meteor/templating';
import {Tracker} from 'meteor/tracker'; // make sure to import Tracker
import './body.html';
import {PlayersList} from '../api/players.js';

Template.leaderboard.onCreated(function() {
  // make sure to subscribe to your publication in the onCreated lifecycle call
  // to ensure the playerList is available for the component
  // http://blazejs.org/api/templates.html#Blaze-TemplateInstance-subscribe
  this.subscribe('<publication-name>');
});

Template.leaderboard.helpers({
  'player': function(){
    return PlayersList.find();
  },

  // provide data to the helper
  // http://blazejs.org/guide/reusable-components.html#Pass-data-into-helpers
  'selectedClass': function(playerId) {
    // use Session.equals for efficiency
    // https://docs.meteor.com/api/session.html
    return Session.equals('selectedPlayer', playerId)
      ? 'selected' : '';
  }  
});

Template.leaderboard.events({
    'click .player': function() {
        var playerId = this._id;
        Session.set('selectedPlayer', playerId);
    }
});

Remember, it's important to understand what this represents in your helpers and event maps.

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

Searching and Substituting Elements with jQuery in a Text String

After making an Ajax call, I have retrieved HTML as a string. headings .... <div class="wrapper"> <input type="text" name="email" value="" /> </div> .... I have extracted the .wrapper and input elements from the HTML string. var el ...

Looking to create a pop-up using javascript, css, or jQuery?

When visiting digg.com and clicking the login button, a sleek in-screen popup appears to input user data. I'm curious about the best way to achieve this on my own site. It is built with RoR and includes some Javascript elements. Searching for "javasc ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server: historyApiFallback: { index: 'index.html', } Now, when transitioning to production mode, I wanted to replicate the ...

Tips for loading and updating data simultaneously in VUEJS from a single input

Currently, the data is displayed in a span tag with an input for updating it Is it possible to fetch data from an API, load it into an input field, update the input with new information, and send it back? What are the best approaches for achieving this? ...

Tips for submitting an e-mail through an HTML form with the help of Node.js and Gulp

Today, I've been tackling the challenge of creating an HTML contact form that can send an email using Node.js and Gulp. However, I'm struggling to find a solution. Using a relative path to a simple .PHP file doesn't seem to be working, so it ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

Ways to extract a number that comes after a specific word in a URL

I have a URL and need to extract a specific value from it by removing a certain step. I am looking for a regex solution to accomplish this task For example, if I have the window.location.href, the URL might look like this: https://mypage/route/step-1/mor ...

Creating a collection by gathering data from interactive fields with the help of AngularJS

I have a project to create an attendance system for employees. The system requires me to track the attendance status of each employee by generating a dynamic form with text input fields and checkboxes using angularjs ng-repeat inside a table. This form wil ...

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

Unsure of how to create a record of calculations made on the calculator

I am struggling with creating a calculator that includes a history feature. I have the basic functioning of the calculator working, but now I want to modify it so that it displays a history of operations performed by the user. The goal is for the history t ...

Guide to Deactivating the ENTER Key Functionality in React Material UI Autocomplete Form

My React component features a Material UI Autocomplete form that is working perfectly, except for one issue - when the user hits ENTER, the input field gets cleared. I simply want to prevent the input field from being cleared when ENTER key is pressed. Des ...

Issues with integrating Django and Mongoengine fixtures

My setup involves utilizing Mongoengine(version: 0.9.0) with Django(version: 1.8). Here is the snippet from my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.dummy' } } MONGO_DBNAME = " ...

Generating a fresh array by filtering out elements with specific properties using the .map() method

Within my React application, there exists an array containing key value pairs where each pair corresponds to a checkbox. Upon checking the checkbox, the value of the corresponding key switches between true and false. The structure of the data retrieved is ...

Is there a way to emphasize a particular day on the calendar obtained from the URL?

I have implemented FullCalendar functionality to enable users to select a specific date, retrieve data from a database, and then reload the page with that data. The page is updated with the selected date in the URL. However, when the page reloads, althoug ...

When making a Post Request, the Req.body is found to be empty

Here is the code snippet from various files: In App.js file: app.use(express.json({limit:"30mb",extended:true})); app.use(express.urlencoded({extended:true})); In route.js file: router.route("/register").post(registerUser) Importin ...

Can Angular i18n facilitate language switching?

My objective is to switch the language from English (United States) to Indonesia using a button. View Source Code https://i.sstatic.net/0YlfWaCY.gif The issue is that the tutorial does not cover how to implement the language change feature. Why opt for ...

Is there a way to modify this within a constructor once the item has been chosen from a randomly generated array?

If I use the following code: card01.state = 3; console.log(card01); I can modify the state, but I'm interested in updating the state of the card chosen by the random function. class Item { constructor(name, state) { this.name = name; thi ...

Swapping Out Models in Three.js: A Guide to Replacing Object3D Models

I'm attempting to swap out an object3D for a character model, while retaining all of its attributes like the position. var object = new THREE.Object3D( ); object = models.character[0].clone( ); object.position.set( 100, 230, 15 ); scene.add( object.sc ...