1+ window . onload = main ;
2+
3+ function main ( ) {
4+ const url = 'https://opentdb.com/api.php?amount=5' ;
5+ fetchData ( url ) . then ( response => {
6+ AddToDOM ( response ) ;
7+ } )
8+ . catch ( error => { console . log ( error ) } ) ;
9+ } ;
10+
11+ function AddToDOM ( Data ) {
12+ const trivia = Data . results ;
13+ const questions = document . querySelector ( '.questions' ) ;
14+ const div = document . createElement ( 'div' ) ;
15+ const answers = document . getElementsByClassName ( 'answer' ) ;
16+
17+ trivia . forEach ( array => {
18+ const question = document . createElement ( 'p' ) ;
19+ const answer = document . createElement ( 'p' ) ;
20+
21+ question . textContent = decodeHTML ( array . question ) ;
22+ question . classList . add ( 'question' ) ;
23+ answer . textContent = decodeHTML ( array . correct_answer ) ;
24+ answer . style . display = 'none' ;
25+ answer . classList . add ( 'answer' ) ;
26+
27+ div . appendChild ( question ) ;
28+ div . appendChild ( answer ) ;
29+ questions . appendChild ( div ) ;
30+
31+ close ( ) ;
32+ function open ( ) {
33+ answer . style . display = 'block' ;
34+ question . removeEventListener ( 'click' , open ) ;
35+ question . addEventListener ( 'click' , close ) ;
36+ } ;
37+ function close ( ) {
38+ answer . style . display = 'none' ;
39+ question . removeEventListener ( 'click' , close ) ;
40+ question . addEventListener ( 'click' , open ) ;
41+ } ;
42+
43+ document . addEventListener ( 'click' , function ( event ) {
44+ const isClickInsideElement = div . contains ( event . target ) ;
45+ if ( ! isClickInsideElement ) {
46+ Array . from ( answers ) . forEach ( element => {
47+ element . style . display = 'none' ;
48+ close ( ) ;
49+ } ) ;
50+ } ;
51+ } ) ;
52+ } ) ;
53+ } ;
54+
55+ function decodeHTML ( html ) {
56+ const txt = document . createElement ( 'textarea' ) ;
57+ txt . innerHTML = html ;
58+ return txt . value ;
59+ } ;
60+
61+ async function fetchData ( url ) {
62+ const Data = await fetch ( url ) ;
63+ return await Data . json ( ) ;
64+ } ;
0 commit comments