Tumblr's images viewer

It shows up one image every 5 seconds (one per post). You can go forward and backward using cursor arrows.

by Génesis García Morilla

HTML

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

CSS

body {
  background: black;
}

img {
    width: 100%;
    height: auto;
}

JavaScript

const index = (() => {
  const api = 'https://api.tumblr.com/v2/blog/'
  const api_key = 'api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4'

  /**
   Checks if an url is valid or not
   @param str 'string' URL
   @return boolean
  */
  function valid_url(str) {
    const pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
      '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
    if(!pattern.test(str)) {
      alert('Please enter a valid URL.')
      return false
    } else return true
  }

  /**
   Start showing posts' images
   @param posts [array]
  */
  function start(posts) {
    const timeout = 5000 // 5s
    let $container_ = document.querySelector('#container')
    let next_timer_ = setTimeout(go, 0)
    let i = -1

    /**
     Go back and forth
     @param direction 'string' previous to go backward, anything else to go forward
    */
    function go(direction) {
      clearTimeout(next_timer_)

      if (direction && direction == 'previous') {
        // If we are at the begginng, it doesn't do anything
        if (i < 1) return;
        i--
      } else i++

      console.log(i)
      // Finished when there are no more posts
      if (i >= posts.length) return;

      console.log(posts[i].photos[0].original_size.url)
      // If there are no images, next post
      if (!posts[i].photos.length) go()

      // Load image
      $container_.innerHTML =
      '<img src="' + posts[i].photos[0].original_size.url + '">'

      // Next image X seconds after the last image has loaded
      const $img = document.querySelector('img')
      if ($img.complete) {
        next_timer_ = setTimeout(go, 5000)
      } else {
        $img.addEventListener('load', () => {
          next_timer_ = setTimeout(go, timeout)
       ...