I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the user clicks an option. Additionally, all items within the v-for loop are changing colors based on the correctness of the answers. However, my main issue lies in isolating just one item within the v-for loop to change color.
Below is the relevant HTML code snippet:
<button type="button" class="btn answer" v-for="option in options" @click="checkAnswer(option)" @click="selected = option" :style="{backgroundColor: colour}">
{{option}}<br/>
</button>
<button type="button" @click="getQ" @click="shuffle(options)" class="btn button next">Next</button>
Here is the corresponding JavaScript section:
let colour = Vue.ref('');
let selected = Vue.ref('');
let options = Vue.ref([correctAnswer, incorrectAnswerOne, incorrectAnswerTwo, incorrectAnswerThree]);
// Methods
let shuffle = function(options) {
let num = options.length, t, raInt;
//while there are remaining elements to shuffle
while (num) {
//choose random
raInt = Math.floor(Math.random() * num--);
//swap with current element
t = options[num];
options[num] = options[raInt];
options[raInt] = t;
}
return options;
};
let checkAnswer = function(clicked) {
console.log(clicked.value);
console.log(correctAnswer.value);
if (clicked.value == correctAnswer.value) {
this.result = "Correct!";
this.colour = "green";
} else {
this.result = "Incorrect!";
this.colour = "red";
};
};
And here is some CSS styling:
.answer {
width: 100%;
background-color: #dbdbdb;
padding: 4% 2%;
margin: 1 0;
}
.answer:hover {
background-color: #c2c2c2
}
I haven't experimented much with different solutions yet. I'm unsure about how to tackle the task at hand. In a previous project, I successfully styled one div based on the selection of another div, but modifying only a specific part of a v-for loop remains uncharted territory for me. Any assistance would be greatly appreciated. Thank you!