Skip to content

Instantly share code, notes, and snippets.

@m0n01d
Last active February 4, 2021 13:58
Show Gist options
  • Save m0n01d/c3e1afe2be4b617a3935eb8ffa57b58d to your computer and use it in GitHub Desktop.
Save m0n01d/c3e1afe2be4b617a3935eb8ffa57b58d to your computer and use it in GitHub Desktop.
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