Instapedia

Playing with Google Search results JSON as well as click and keydown events.

by psyne

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css">
<div id="container">
<h1>Instapedia</h1>

    
<input id="search" type="text" class="input-block-level">
    <button id="clearResults" class="btn input-block-level">Clear</button>


<div id="links"></div>
</div>

CSS

#container{
    padding 20px;
    margin: 20px;
}

JavaScript

$('#search').keydown(function() {

    //Grab the value of the search field.
    var queryItem = $(this).val();

    function queryWikipedia(query) {
        var queryString = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' + query + '&as_sitesearch=en.wikipedia.org&callback=?';
        
        $.getJSON( queryString, function(data) {
            var items = [];
            // add each result to the items array so we can add all the elements at once limiting the reflows needed.
            $.each(data.responseData.results, function(i, val) {
                items.push('<li><a href="' + val.url + '" target="_blank"><h4>' + val.titleNoFormatting.replace(' - Wikipedia, the free encyclopedia', "") + '</a></h4><p>' + val.content + '</p></li>');
            });


            $('<ul/>', {
                'class': 'wikipedia-results',
                html: items.join(' ')
            }).appendTo('#links');
        });

    }

    if (queryItem.length > 3) {
        queryWikipedia(queryItem);
    }

});

$('#clearResults').click(function(e) {
    e.preventDefault();
    $('#links').empty();

});