1+ const questions = [
2+ {
3+ question : "What is the capital of France?" ,
4+ options : [ "London" , "Berlin" , "Paris" , "Madrid" ] ,
5+ answer : "Paris"
6+ } ,
7+ {
8+ question : "Which programming language is known for its use in web development?" ,
9+ options : [ "Java" , "Python" , "JavaScript" , "C++" ] ,
10+ answer : "JavaScript"
11+ } ,
12+ {
13+ question : "What is the result of 2 + 2?" ,
14+ options : [ "3" , "4" , "5" , "6" ] ,
15+ answer : "4"
16+ } ,
17+ {
18+ question : "What does HTML stand for?" ,
19+ options : [ "Hyper Text Markup Language" , "High-Level Text Machine Language" , "Hyperlink and Text Markup Language" , "Home Tool Markup Language" ] ,
20+ answer : "Hyper Text Markup Language"
21+ }
22+ ] ;
23+
24+
25+ const nextBtn = document . getElementById ( 'next-btn' )
26+ const quizContainer = document . getElementById ( 'quiz-container' )
27+ const options = document . getElementById ( 'options' ) . querySelectorAll ( '.btn' ) ;
28+ const question = document . getElementById ( 'question' )
29+ let score = 0 ;
30+ let index = 0 ;
31+ let answer ;
32+
33+
34+ const loadQuestion = ( ) => {
35+ nextBtn . setAttribute ( 'disabled' , 'true' )
36+ if ( index > 0 ) {
37+ resetAnswer ( )
38+ }
39+ question . innerHTML = `${ index + 1 } . ${ questions [ index ] . question } `
40+ options . forEach ( ( option , i ) => {
41+ option . textContent = questions [ index ] . options [ i ] ;
42+ option . addEventListener ( 'click' , ( ) => {
43+
44+ nextBtn . removeAttribute ( 'disabled' )
45+ resetAnswer ( )
46+ option . classList . replace ( 'btn-primary' , 'btn-dark' )
47+ answer = option . textContent
48+ } )
49+ } )
50+ }
51+
52+ nextBtn . addEventListener ( 'click' , ( ) => {
53+
54+ checkAnswer ( )
55+ index ++ ;
56+ if ( index < questions . length ) {
57+ loadQuestion ( )
58+ } else {
59+ endQuiz ( )
60+ }
61+
62+ } )
63+
64+ const endQuiz = ( ) => {
65+ quizContainer . innerHTML = `
66+ <h1>Your Score is ${ score } /${ questions . length } .</h1>
67+ <button class="btn btn-success mt-3" onclick="window.location.reload()">Play Again</button>
68+ `
69+ }
70+
71+ const checkAnswer = ( ) => {
72+ if ( answer == questions [ index ] . answer ) {
73+ score ++ ;
74+ }
75+
76+ }
77+
78+ const resetAnswer = ( ) => {
79+ options . forEach ( ( option ) => {
80+ if ( option . classList . contains ( 'btn-dark' ) ) {
81+ option . classList . replace ( 'btn-dark' , 'btn-primary' )
82+ }
83+ } )
84+
85+ }
86+ loadQuestion ( )
0 commit comments