Skip to content

Instantly share code, notes, and snippets.

@imdwit

imdwit/giphy.js

Last active Mar 19, 2017
Embed
What would you like to do?
giphy homework in vanilla js
/*
index.html
<div>
<div id="btns">
<button data-query="cats">cats</button>
</div>
<input id="add-topic" placeholder="add a topic" />
</div>
<div id="gifs"></div>
<script src="giphy.js"></script>
*/
const $btns = document.getElementById('btns');
const $gifs = document.getElementById('gifs');
const $addTopic = document.getElementById('add-topic');
const state = {
gifs: [],
};
const fetchGifs = (q) => {
const api_key = 'dc6zaTOxFJmzC';
const giphyApi = 'http://api.giphy.com/v1/gifs/search';
const url = `${giphyApi}?q=${q}&api_key=${api_key}`;
return fetch(url)
.then(res => res.json())
.then(res => res.data)
};
function setGifs(gifs, mapWith, cb) {
this.gifs = gifs.map(mapWith);
cb(this.gifs);
}
function togglePlaying(e, cb) {
const index = e.target.dataset.gifIndex;
this.gifs = this.gifs.map((gif, i) => {
if (i == index) {
return Object.assign({}, gif, {isPlaying: !gif.isPlaying});
}
return gif;
});
cb(this.gifs);
}
const renderGif = ({ index, isPlaying, playing, still}) => {
return `
<div class="gif">
<img data-gif-index="${index}" src="${isPlaying ? playing : still}" />
</div>
`;
};
const renderGifs = function (gifs) {
this.innerHTML = '';
this.innerHTML = gifs.map(renderGif).join('');
}.bind($gifs);
const transformGif = (gif, index) => {
const id = gif.id;
const { fixed_width, fixed_width_still } = gif.images;
const playing = fixed_width.url;
const still = fixed_width_still.url;
return Object.assign({}, { isPlaying: false, playing, still, index });
};
const onFetch = gifs => setGifs.call(state, gifs, transformGif, renderGifs)
function loadGifs(query) {
fetchGifs(query)
.then(onFetch);
}
function addTopic({which, target}) {
if (which === 13) {
const topic = target.value;
target.value = '';
$btns.innerHTML += `<button>${topic}</button>`;
loadGifs(topic);
}
}
$gifs.addEventListener('click', (e) => togglePlaying.call(state, e, renderGifs), false);
$btns.addEventListener('click', e => loadGifs(e.target.innerText), false);
$addTopic.addEventListener('keyup', addTopic, false);
loadGifs('cats');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.