Reputation:
document.querySelectorAll(".answer").forEach((answer) => {
//getting .answer from HTML and adding a click function
answer.addEventListener("click", (event) => {
if (event.target.dataset) {
document.querySelectorAll(".answer").forEach(e => e.classList.remove('selected'))
answer.classList.add('selected')
}
if (event.target.dataset.correct == "true") {
correctAnswer++
}
});
});
.selected{
border: 5px solid black;
}
<h3 id="question"></h3>
<div class="answers">
<button type="button" id="answer1" class="answer"></button>
<button type="button" id="answer2" class="answer"></button>
<button type="button" id="answer3" class="answer"></button>
<button type="button" id="answer4" class="answer"></button>
</div>
I have my question and answers in an object, they are shuffled and the answers are put into these buttons, then the selected button get a border. How do I make it where only one button can be selected at a time, and if 2 are selected, the first one is unselected.
Upvotes: 1
Views: 992
Reputation: 31987
It's better to use a class to apply these styles.
Simply remove the class from every element before adding the class to the current element.
document.querySelectorAll(".answer").forEach((answer) => {
//getting .answer from HTML and adding a click function
answer.addEventListener("click", (event) => {
if (event.target.dataset) {
document.querySelectorAll(".answer").forEach(e => e.classList.remove('selected'))
answer.classList.add('selected')
}
if (event.target.dataset.correct == "true") {
correctAnswer++
}
});
});
.selected{
border:5px solid black;
}
<h3 id="question"></h3>
<div class="answers">
<button type="button" id="answer1" class="answer">1</button>
<button type="button" id="answer2" class="answer">2</button>
<button type="button" id="answer3" class="answer">3</button>
<button type="button" id="answer4" class="answer">4</button>
</div>
Upvotes: 1