Skip to content

Instantly share code, notes, and snippets.

@rich-at-thinkful
Created February 8, 2017 19:46
Show Gist options
  • Save rich-at-thinkful/69cdeaab00d58d635a4807c9882f3c97 to your computer and use it in GitHub Desktop.
Save rich-at-thinkful/69cdeaab00d58d635a4807c9882f3c97 to your computer and use it in GitHub Desktop.
const BASE_SEARCH_URL = 'http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC';
const appState = {
results: [],
history: []
};
function clearSearchField(){
$('#search-field').val('');
}
function setResults(state, results){
state.results = results;
}
function addSearchToHistory(state, searchTerm){
state.history.push(searchTerm);
}
function renderResults(state){
const el = $('.results-list');
console.log(state.results);
const resultsHtml = state.results.data.map(item => {
return `<li><img width="150" src="${item.images.downsized_still.url}" /></li>`;
});
el.html(resultsHtml);
}
function renderHistory(state){
const el = $('.history-list');
const historyHtml = state.history.map(h => `<li>${h}</li>`).join('');
el.html(historyHtml);
}
function renderAll(state){
renderResults(state);
renderHistory(state);
}
function fetchFromGiphy(searchQuery){
$.getJSON(`${BASE_SEARCH_URL}`, {q: searchQuery}, (response) => {
setResults(appState, response);
addSearchToHistory(appState, searchQuery);
clearSearchField();
renderAll(appState);
});
}
function init(){
$('#search').submit(e => {
e.preventDefault();
const searchTerm = $('#search-field').val();
fetchFromGiphy(searchTerm);
});
}
$(init);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment