I have a collection of three colored buttons. My goal is to allow users to select one button at a time, triggering it to be highlighted while the others are unselected. Each button corresponds to an object with a property called isSelected that can be set to true or false. While I am aware that achieving this functionality with jQuery would be straightforward, I am committed to mastering JavaScript objects.
The snippet below contains what I believe to be the pertinent code segments for troubleshooting, excluding any HTML and CSS components. You can access the complete application on CodePen: http://codepen.io/isachenx/pen/LxEOOR
My approach involves toggling the isSelected property between true and false for each button instance. If the value is true, a css class named .selected should be applied in the generated HTML string; otherwise, the class shouldn't be included. On every click event for a list item element, I aim to re-render the respective part of the string...
// Define a constructor function
function Selector(color) {
this.color = color;
this.isSelected = false;
}
// Methods for selecting/deselecting list items
Selector.prototype.selectColor = function() {
this.isSelected = true;
}
Selector.prototype.deselectColor = function() {
this.isSelected = false;
}
// Render list item as HTML string
Selector.prototype.toHTML = function() {
let htmlString = "";
htmlString += '<li id="' + this.color + '" class="' + this.color;
if (this.isSelected) {
htmlString += ' selected';
}
htmlString += '"></li>';
return htmlString;
}
// Constructor for rendering all list items
function Controls() {
this.selectors = [];
}
Controls.prototype.add = function(selector) {
this.selectors.push(selector);
}
Controls.prototype.renderInElement = function(list) {
list.innerHTML = '';
for (let i = 0; i < this.selectors.length; i++) {
list.innerHTML += this.selectors[i].toHTML();
}
}
let controls = new Controls();
let red = new Selector('red');
let blue = new Selector('blue');
let yellow = new Selector('yellow');
controls.add(red);
controls.add(blue);
controls.add(yellow);
let controlElement = document.getElementById('controlButtons');
controls.renderInElement(controlElement);
let redButton = document.getElementById('red');
redButton.onclick = function() {
red.selectColor();
blue.deselectColor();
yellow.deselectColor();
controls.renderInElement(controlElement);
};
let blueButton = document.getElementById('blue');
blueButton.onclick = function() {
blue.selectColor();
red.deselectColor();
yellow.deselectColor();
controls.renderInElement(controlElement);
};
let yellowButton = document.getElementById('yellow');
yellowButton.onclick = function() {
yellow.selectColor();
red.deselectColor();
blue.deselectColor();
controls.renderInElement(controlElement);
};