Hello Everyone!
I am currently coding a project as a hobby which involves using the open trivia API however I am struggling to use it. I have coded it so that the user can choose the parameters as to which category, difficulty and the amount of questions that they would like to have in the quiz. I had managed to make it successful when coding it however when I added error handling into it, it no longer works despite going back and deleting it. I have not changed anything however I just am a bit confused and would appreciate anyone’s help. I will attach the JavaScript code down below for people who are willing to help to read. Thank you in advance if you do help!
const Progression = document.querySelector(‘.progression-bar’),
Progressiontext = document.querySelector(‘.progression-text’);
const progress = (value) => {
const percent = (value / time) * 100;
Progression.style.width = ${percent}%
;
Progressiontext.innerHTML = ${value}
;
};
let questions = ,
Time = 30,
score = 0,
Currentq,
timer;
const startGame = async () => {
const num = sessionStorage.getItem(“num”);
const cat = sessionStorage.getItem(“cat”);
const diff = sessionStorage.getItem(“diff”);
const url = https://opentdb.com/api.php?amount=5&category=1&difficulty=easy&type=multiple
;
// Log the parameter values
console.log(‘Parameters:’, num, cat, diff);
// Log the URL
console.log(‘URL:’, url);
try {
const response = await fetch(url);
const data = await response.json();
if (data.response_code !== 0) {
console.error(‘API returned an error:’, data);
if (data.response_code === 1) {
alert(‘Not enough questions in the selected category. Please select a different category or reduce the number of questions.’);
}
return;
}
questions = data.results;
if (questions[0]) {
setTimeout(() => {
Currentq = 1;
displayQuestion(questions[0]);
}, 1000);
} else {
console.error(‘No questions were fetched’);
}
} catch (error) {
console.error(‘Failed to fetch questions:’, error);
}
};
startGame();
const displayQuestion = (question) => {
const questiontxt = document.querySelector(‘.question-text’),
optioncontainer = document.querySelector(‘.option-container’);
questionnum = document.querySelector(‘.question-num’);
questiontxt.innerHTML = question.question;
const answers = question.incorrect_answers.concat([question.correct_answer.toString()]);
optioncontainer.innerHTML = ‘’;
answers.sort(() => Math.random() - 0.5);
answers.forEach((answer) => {
optioncontainer.innerHTML += <div class = 'answer-options'> <span class = 'answer-text'>${answer}</span> <span class = 'text-box'> <span class = 'checkmark'>x</span> </span> </div>
;
});
};