1/**
2* Try this example at https://alpsquid.github.io/quizlib
3*/
4
5/* DOKUWIKI:include scripts/quizlib.js */
6
7var quiz;
8
9function quizlibShowResults(quizname, quizanswers) {
10    quiz = new Quiz(quizname, quizanswers);
11    // Check answers and continue if all questions have been answered
12    if (quiz.checkAnswers()) {
13        var quizScorePercent = quiz.result.scorePercentFormatted; // The unformatted percentage is a decimal in range 0 - 1
14        var quizResultElement = document.getElementById('quizlib-result');
15        quizResultElement.style.display = 'block';
16        document.getElementById('quiz-score').innerHTML = quiz.result.score.toString();
17        document.getElementById('quiz-max-score').innerHTML = quiz.result.totalQuestions.toString();
18        document.getElementById('quiz-percent').innerHTML = quizScorePercent.toString();
19
20        // Change background colour of results div according to score percent
21        if (quizScorePercent >= 75) quizResultElement.style.backgroundColor = '#4caf50';
22        else if (quizScorePercent >= 50) quizResultElement.style.backgroundColor = '#ffc107';
23        else if (quizScorePercent >= 25) quizResultElement.style.backgroundColor = '#ff9800';
24        else if (quizScorePercent >= 0) quizResultElement.style.backgroundColor = '#f44336';
25
26        // Highlight questions according to whether they were correctly answered. The callback allows us to highlight/show the correct answer
27        quiz.highlightResults(handleAnswers);
28    }
29}
30
31/** Callback for Quiz.highlightResults. Highlights the correct answers of incorrectly answered questions
32 * Parameters are: the question element, question number, correctly answered flag
33 */
34function handleAnswers(question, no, correct) {
35    if (!correct) {
36        var answers = question.getElementsByTagName('input');
37        for (var i = 0; i < answers.length; i++) {
38            if (answers[i].type === "checkbox" || answers[i].type === "radio"){
39                // If the current input element is part of the correct answer, highlight it
40                if (quiz.answers[no].indexOf(answers[i].value) > -1) {
41                    answers[i].parentNode.classList.add(quiz.Classes.CORRECT);
42                }
43            } else {
44                // If the input is anything other than a checkbox or radio button, show the correct answer next to the element
45                var correctAnswer = document.createElement('span');
46                correctAnswer.classList.add(quiz.Classes.CORRECT);
47                correctAnswer.classList.add(quiz.Classes.TEMP); // quiz.checkAnswers will automatically remove elements with the temp class
48                correctAnswer.innerHTML = quiz.answers[no];
49                correctAnswer.style.marginLeft = '10px';
50                answers[i].parentNode.insertBefore(correctAnswer, answers[i].nextSibling);
51            }
52        }
53    }
54}
55