JavaScript: Wikipedia Viewer

Demo: Wikipedia Viewer

HTML Code:

<body>
<div class="container">
<h1>Wikipedia Search</h1>
<p>A Free Code Camp Intermediate Project</p><br/>
<div class="wrapper">
<input class="form-control" id="searchItem"></input>
<button id="search" type="button" class="btn">&#128269;</button>
</div>
<br/><br/>
<ul id="output" class="list-unstyled">


</ul>
</div>
</body>

CSS Code:

body{
text-align: center;
font-family:"Garamond";
}
p{
display:block;
margin:auto;
}

#searchItem{
box-shadow: inset 2px 2px 2px 2px grey, 2px 2px 2px 2px grey;
position:relative;
float: left;
height:42px;
width: 100%;
}
#search{
box-shadow: 2px 2px 3px 2px transparent;
position: absolute;
top: 50%;
margin-left: -56px;
margin-top: 28px;
z-index: 1;
color: black;
background-color: Transparent;
border: 0;
font-weight: bold;
height:39px;
}
#search:hover{
color: red;
box-shadow: inset 2px 2px 3px 2px grey;
}

#output{
display:block;
}

JavaScript Code:

$(document).ready(function(){

$(function() { $("#searchItem").focus();}); // This will automatically put the cursor on the search box
$("#searchItem").keypress(function(key){if(key.which==13){$("#search").click();}});

$("#search").click(function(){
var searchItem=$("#searchItem").val();
var url="https://en.wikipedia.org/w/api.php?action=opensearch&search="+searchItem+"&format=json&callback=?";
$("#search").hide();

$.ajax({
type:"GET",
url:url,
async:false,
dataType:"json",
success: function(data){
$("#output").html(""); // clear the prior outputs
$("#searchItem").val(''); // clear the prior search field
for (var i =0; i<data[1].length; i++){
// Use a JSON viewer to preview the API call prior to formulating outputs such as this
$("#output").prepend("<li><a href="+data[3][i]+">"+data[1][i]+"</a><p>"+data[2][i]+"</p></li><hr>");
}
$(function() { $("#searchItem").focus();});
},
error: function(errorMessage){
alert("Error");
}

}); // closes AJAX function


}); // closes Search Click Function


}); // closes document ready function

Leave a Reply

Your email address will not be published. Required fields are marked *