TLIYGiphy

A simple gif fetching api, based on the Giphy API, depending on which tags you give it.

by thelifeisyours

HTML

<div id="main-container">
</div>

CSS

html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background: #272727;
}

#main-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  border: solid orange 2px;
}

#main-container>img {
  max-width: 8em;
}
}

JavaScript

class TLIYGiphy {
  constructor() {
    this.GIPHY_API_KEY = "CaSL6msn6ZiI41msBeEsg5n2KgImDh9c";
    this.gifs = [];

    this.gif = class {
      constructor(_container, _url, _delay) {
        this.url = _url;
        this.container = _container;
        this.lifetime = _delay;

        this.isDead = false;
        this.destoyParent = false;

        this.gif = new Image();

        this.gif.addEventListener('load', () => {
          this.display();

          setTimeout(() => {
            this.isDead = true;
          }, this.lifetime);
        });

        this.addSrc();
      }


      addSrc() {
        this.gif.src = this.url;
      }


      display() {
        this.container.append(this.gif);
      }

      destroy() {
        this.container.querySelectorAll('img').forEach((img) => {
          if (img.src == this.url) {
            this.destroyParent ? img.parentNode.remove() : img.remove();
          }
        });
      }
    }
  }

  async spawnGif(_container, _tags, options) {

    let url = await this.getGifURL(_tags);
    let calculateDelay = await this.calculateDelay(url);

    let newGif = new this.gif(_container, url);

    let {
      destroyParent,
      fixedDelay
    } = (options != (null || undefined)) ? options: {};

    newGif.destroyParent = destroyParent ? true : false;
    newGif.lifetime = fixedDelay || calculateDelay;

    this.gifs.push(newGif);
    this.updateGifs();
  }

  async getGifURL(tag) {
    let response = await this.request(`https://api.giphy.com/v1/gifs/random?tag=${tag}&api_key=${this.GIPHY_API_KEY}&limit=5`)
      .then((res) => {
        return JSON.parse(res);
      }).catch((err) => {
        console.error(`Error while fetching Gif: ${err}`);
      });

    return response.data.image_url;
  }

  updateGifs() {
    //console.log(this.gifs);

    this.gifs.forEach((gif, index) => {
      //console.log(index);
      //console.log(gif);

      //console.log(gif.isDead);
      if (gif.isDead) {
        gif.destroy();
   ...