I'm trying to do a trivia game, with 10 random questions, but I'm having trouble with the action for the next question. The click action is working for the first next question, but for every time I click the button it's being executed by 2x and starts marking every answer as wrong. I've tried to put the trivia() function outside the API function, but then the index (i) is not receiving the new number. I've tried the preventDefault, but it seems it's not working. I want to go to the next question even if the answer is wrong.
$(document).ready(function() {
$.get('https://opentdb.com/api.php?amount=10&category=17&type=boolean', function(dados) {
//console.log(dados.results[i].question, dados.results[i].correct_answer)
trivia();
function trivia() {
let i = newNumber();
console.log(i, dados.results[i].question, dados.results[i].correct_answer)
let right = dados.results[i].correct_answer;
let wrong = dados.results[i].incorrect_answers;
$('#question').html(dados.results[i].question);
if (right == 'True') {
$('#true').html(right)
$('#true').on('click', function() {
$(this).addClass('right')
})
$('#false').html(wrong)
$('#false').on('click', function() {
$(this).addClass('wrong');
})
} else {
$('#false').html(right)
$('#false').on('click', function() {
$(this).addClass('right')
});
$('#true').html(wrong)
$('#true').on('click', function() {
$(this).addClass('wrong');
})
}
$('#next').on('click', function(event) {
event.preventDefault();
nextQ();
console.log('clicou proximo')
trivia();
})
}
})
})
function newNumber() {
var numeros = [];
while (numeros.length < 10) {
var aleatorio = Math.floor(Math.random() * 10);
if (!numeros.includes(aleatorio))
numeros.push(aleatorio);
}
return numeros[Math.floor(Math.random() * 10)]
}
function nextQ() {
if ($('.answer').hasClass('right') || $('.answer').hasClass('wrong')) {
if ($('.answer').hasClass('right') && $('.answer').hasClass('wrong')) {
$('.answer').removeClass('right')
$('.answer').removeClass('wrong')
}
if ($('.answer').hasClass('right')) {
$('.answer').removeClass('right');
}
if ($('.answer').hasClass('wrong')) {
$('.answer').removeClass('wrong');
}
}
}