Pokemon Api Sample

samples what you can do with the pokemon api "pokeapi.co"

by Daniel Latimer

HTML

<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="log"></div>
<div id="pokemon" class="vert-space">
  <div>
    <span id="name" class="name">Name: TBD</span>
  </div>
  <div>
    <span id="type" class="type">Type: TBD</span>
  </div>
  <div>
    <span id="pictures"></span>
  </div>
</div>
<img id="background" class="bgimg"/>

CSS

.vert-space {
  margin-top: 30px
}

.name {
  font-family: Helvetica, Verdana, sans-serif;
  font-size: 5em;
  left: -100%;
  position: relative;
}

.type {
  font-family: Helvetica, Verdana, sans-serif;
  font-size: 2em;
  left: -100%;
  position: relative;
}

.bgimg {
    z-index: -1;
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    width: 100%;
}

.fadeIn {
    opacity: 0.6;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
}

.slideIn {
  left: 0;
  -webkit-transition: 1s ease-in-out;
  -moz-transition: 1s ease-in-out;
  -ms-transition: 1s ease-in-out;
  -o-transition: 1s ease-in-out;
  transition: 1s ease-in-out;
}

JavaScript

function log(message) {
	const log = $('#log')
  const currentMessage = log.html()
  log.html(currentMessage + '<br>' + message)
}

log("now loading...")

$.get('https://pokeapi.co/api/v2/type/')
	.then(response => {
    const types = response.results
    const randomType = _.sample(types)

		log("Type " + randomType.name + " selected, querying pokemon of that type")
    $('#type').html('Type: ' + _.startCase(randomType.name));
    $('#type').addClass('slideIn')
    
    return $.get(randomType.url);
  })
  .then(response => {
  	const pokemonOfSelectedType = response.pokemon
    const randomPokemon = _.sample(pokemonOfSelectedType).pokemon

    log("Pokemon " + randomPokemon.name + " was selected, querying pictures of that pokemon")
    $('#name').html(_.startCase(randomPokemon.name))
    $('#name').addClass('slideIn')

  	return $.get(randomPokemon.url)
  })
  .then(response => {
  	const pictures = _.toPairs(response.sprites).filter(([key, value]) => value !== null)
  	const pictureUrls = pictures.map(([key, value]) => value)
    
    const pictureElements = pictureUrls.map(picture => "<img src=\"" + picture + "\" />")
    const backgroundPicture = _.get(_.first(pictures.filter(([name, url]) => _.includes(name, 'front'))) || _.sample(pictures), '[1]')
    
    log(pictureUrls.length + " pictures were found")
    $('#pictures').html(pictureElements)
    $('#background').attr('src', backgroundPicture)
    $('#background').addClass('fadeIn')
  })
  .catch(error => $('#progress').html(JSON.stringify(error)))