-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
112 lines (72 loc) · 2.36 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
$(document).ready(function(){
fetchAsyncData()
$(".ans-btn").on('click', function(event){
if(event.target.getAttribute('data-answer') === answer){
$(this).addClass("correct-ans")
$(".btn").attr('disabled', 'true')
$(".py-5.text-center").css("cursor", "no-drop")
$("#nxt-btn").css("display", "initial")
$("#nxt-btn").removeAttr("disabled")
$("#nxt-btn").text("Next")
}
else{
$(this).addClass(" wrong-ans")
$(".btn").attr('disabled', 'true')
$(".py-5.text-center").css("cursor", "no-drop")
$("#nxt-btn").css("display", "initial")
$("#nxt-btn").removeAttr("disabled")
$("#nxt-btn").text("Play Again")
}
})
$("#nxt-btn").click(function(){
fetchAsyncData()
$(".btn").removeAttr('disabled')
$(".py-5.text-center").css("cursor", "pointer")
$(".opt").removeClass("correct-ans")
$(".opt").removeClass("wrong-ans")
$("#nxt-btn").text("Next")
$(this).attr("disabled", "true")
})
})
// To feth the data from .json file
function fetchData(){
return new Promise((res, err)=>{
const data = fetch("./data.json").then(response => response.json())
res(data)
})
}
// Generatign random indexes for country and correct/wrong anwers
function gettingRandomNums(data){
const max = data.length
recData = data
const countryIndex = Math.round(Math.random() * max) //Index for country
answer = recData[countryIndex].capital //Global variable for correct answer
const country = recData[countryIndex].country
$("#country").text(recData[countryIndex].country)
const wrongAns = []
for (let i=0; i<3; i++){
let wrongIndex = Math.round(Math.random() * max)
if(wrongIndex != countryIndex){
wrongAns.push(recData[wrongIndex].capital)
}
else{
console.log('mismatched');
}
}
var correctIndex = Math.floor(Math.random() * 4)
wrongAns.splice(correctIndex , 0 , answer)
const answerBox = document.getElementsByClassName("opt")
for(let count = 0; count < answerBox.length; count++){
answerBox[count].innerHTML = wrongAns[count]
answerBox[count].setAttribute("data-answer", wrongAns[count])
}
}
async function fetchAsyncData(){
try{
const data = await fetchData()
gettingRandomNums(data)
}
catch (err){
console.log(err);
}
}