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: