-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiki_viewer.html
102 lines (75 loc) · 3.13 KB
/
wiki_viewer.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wiki Viewer</title>
<link rel="stylesheet" type="text/css" href="./css/wiki_viewer.css" />
<script>
//https://www.freecodecamp.com/challenges/build-a-wikipedia-viewer
window.onload = function () {
var el = document.querySelector( '#wikiViewer' );
var resp = document.querySelector( '#listResults' );
var clearList = document.querySelector( '.clearlist' );
clearList.addEventListener( 'click', function( e ) {
e.preventDefault();
resp.innerHTML = '';
el.elements.search.value = '';
this.classList.add( 'hidden' );
this.classList.remove( 'block' );
});
el.addEventListener( 'submit', function( e ) {
e.preventDefault();
var q = el.elements.search.value;
var url = 'https://en.wikipedia.org/w/api.php?';
var params = 'format=json&gsrlimit=20&action=query&generator=search&origin=*&gsrsearch=' + q;
var request = new XMLHttpRequest();
request.open( 'POST', url + params, true );
request.setRequestHeader( 'Api-User-Agent', 'Example/1.0' );
request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
request.send();
request.onreadystatechange = function() {
if ( this.readyState != 4 ) return;
if ( this.status != 200 ) {
alert( 'Status: ' + ( this.status ? this.statusText : 'error' ) );
return;
} else {
try {
var obj = JSON.parse( this.responseText ).query.pages;
var titleList ='';
//console.log( obj );
for ( var key in obj ) {
var p = obj[key];
titleList += '<li><a target="_blank" href="https://en.wikipedia.org/?curid=' + p.pageid + '">' + p.title + '</a></li>';
}
} catch ( e ) {
titleList = 'No data.';
}
resp.innerHTML = titleList;
clearList.classList.remove( 'hidden' );
clearList.classList.add( 'block' );
}
}
});
}
</script>
</head>
<body>
<section>
<p class="random"><a target="_blank" href="https://en.wikipedia.org/wiki/Special:Random">Random article</a></p>
<form name="wikiViewer" id="wikiViewer" action="" method="get">
<fieldset>
<legend>Wiki_Viewer</legend>
<input placeholder="e.g. The Beatles" type="text" name="search">
<button>Search</button>
<button type="reset">Reset</button>
</fieldset>
</form>
<aside>
<ul id="listResults"></ul>
</aside>
<aside>
<p class="clearlist hidden">Clear</p>
</aside>
</section>
</body>
</html>