Build a Pokémon Search App Project - Tests generate random failures

Tell us what’s happening:

Tests generate random fail results.
Some times I can not pass four tests, sometimes only two. But clearly one of them tests is the test on alert message when pokemon not found. There certainly IS the alert though. Why I can not pass 15th and 18th tests is over my understanding.

### Your code so far

Pokémon Search App
      </div>
      <div class='pokemonname'>
        <h4 id='pokemon-name'></h4>
        <h4 id='pokemon-id'></h4>
      </div>
      <div class='tablescroll'>
        <table id='charcter' class='characteristics'>
          <thead>
            <tr>
              <th class="header">Base</th>
              <th class="header">Stats</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>HP</td>
              <td id='hp'></td>
            </tr>
            <tr>
              <td>Attack</td>
              <td id='attack'></td>
            </tr>
            <tr>
              <td>Defense</td>
              <td id='defense'></td>
            </tr>
            <tr>
              <td>Sp-l attack</td>
              <td id='special-attack'></td>
            </tr>
            <tr>
              <td>Sp-l defence</td>
              <td id='special-defense'></td>
            </tr>
            <tr>
              <td>Speed</td>
              <td id='speed'></td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class='pokemonname weight'>
        <h4 id='weight'></h4>
      </div>
      <div class='pokemonname height'>
        <h4 id='height'></h4>
      </div>
      <div class="pokemonname parent">
      </div>
      <div class='types' id='types'>
        
      </div>
    </div>
    <input id='search-input' type='text' autocomplete="none" required />
    <button id='search-button'> search </button>
  </div>
</main>
<script src="script.js"></script>

const apiUrl = // link to the API

const pokemonImgProxi = //link to an image for empty card

const colours = {
normal: ‘#A8A77A’,
fire: ‘#EE8130’,
water: ‘#6390F0’,
electric: ‘#F7D02C’,
grass: ‘#7AC74C’,
ice: ‘#96D9D6’,
fighting: ‘#C22E28’,
poison: ‘#A33EA1’,
ground: ‘#E2BF65’,
flying: ‘#A98FF3’,
psychic: ‘#F95587’,
bug: ‘#A6B91A’,
rock: ‘#B6A136’,
ghost: ‘#735797’,
dragon: ‘#6F35FC’,
dark: ‘#705746’,
steel: ‘#B7B7CE’,
fairy: ‘#D685AD’,
};

const backgrNameId = document.getElementsByClassName(‘pokemonname’)

const searchInput = document.getElementById(‘search-input’)

const pokemonName = document.getElementById(‘pokemon-name’)

const pokemonImg = document.getElementById(‘imgcontainer’)

const pokemonId = document.getElementById(‘pokemon-id’)

const pokemonWeight = document.getElementById(‘weight’)

const pokemonHeight = document.getElementById(‘height’)

const pokemonTypes = document.getElementsByClassName(‘types’)

const pokemonHp = document.getElementById(‘hp’)

const pokemonAttack = document.getElementById(‘attack’)

const pokemonDefense = document.getElementById(‘defense’)

const pokemonSpecialAttack = document.getElementById(‘special-attack’)

const pokemonSpecialDefense = document.getElementById(‘special-defense’)

const pokemonSpeed = document.getElementById(‘speed’)

const cardBorder = document.getElementById(‘card-border’)

const searchButton = document.getElementById(‘search-button’)

pokemonImg.innerHTML = <img id='sprite' src='${pokemonImgProxi}' alt='pokemon-image' class='pokemonimage'/>

const convertHexToRgb = (hex) => {
hex = hex.slice(1)
return [Number.parseInt(hex.slice(0,2), 16), Number.parseInt(hex.slice(2,4), 16), Number.parseInt(hex.slice(4,6), 16)]
}

const contrastColor = (color) => {
let luminance = Number.parseFloat((0.299color[0] + 0.587color[1] + 0.114*color[2])/255)
return luminance>0.5 ? [0,0,0] : [255,255,255]
}

const lookForPokemon = async (searchStr) => {
if (searchStr) {
let searchResult = await getAllPokemons(apiUrl)
searchResult = searchResult.results.filter(({name, id}) => {return name == searchStr.toLowerCase() || id == searchStr})
if (searchResult.length == 1) {
showPokemon(searchResult[0].url.replace(/http/, ‘https’).slice(0,-1))
} else if (searchResult.length == 0) {
alert(‘Pokémon not found’)
}
}
}

const getAllPokemons = async (url) => {

const response = await fetch(url)

if (!response.ok) {
throw new Error(HTTP error! status: ${response.status});
} else {
return await response.json()
}
}

const showPokemon = async (url) => {
const pokemon = await getAllPokemons(url)
let backColor=convertHexToRgb(colours[‘electric’])
let textColor=contrastColor(backColor)
if (pokemon.types[0].type.name) {
backColor=convertHexToRgb(colours[pokemon.types[0].type.name])
}
let backColorHTML=‘rgb(’ + backColor.join(', ‘) + ‘)’
let textColorHTML=‘rgb(’ + textColor.join(’, ') + ‘)’
backgrNameId[0].style.backgroundColor = backColorHTML
backgrNameId[0].style.color = textColorHTML
backgrNameId[1].style.backgroundColor = backColorHTML
backgrNameId[1].style.color = textColorHTML
backgrNameId[2].style.backgroundColor = backColorHTML
backgrNameId[2].style.color = textColorHTML
backgrNameId[3].style.backgroundColor = backColorHTML
backgrNameId[3].style.color = textColorHTML
cardBorder.style.borderColor = backColorHTML
pokemonName.innerText = pokemon.name.toUpperCase()
pokemonId.innerText = pokemon.id
pokemonWeight.innerText = 'Weight: ’ + pokemon.weight
pokemonHeight.innerText = 'Height: ’ + pokemon.height
pokemonTypes[0].innerHTML = ‘’
pokemonImg.innerHTML = ‘’
for (let typeName of pokemon.types) {
pokemonTypes[0].innerHTML += ‘

’ + typeName.type.name.toUpperCase() + ‘


}
pokemonHp.innerText = pokemon.stats[0].base_stat
pokemonAttack.innerText = pokemon.stats[1].base_stat
pokemonDefense.innerText = pokemon.stats[2].base_stat
pokemonSpecialAttack.innerText = pokemon.stats[3].base_stat
pokemonSpecialDefense.innerText = pokemon.stats[4].base_stat
pokemonSpeed.innerText = pokemon.stats[5].base_stat
pokemonImg.innerHTML = <img id="sprite" src="${pokemon.sprites.front_default}" alt="pokemon-image" class="pokemonimage" />
}

searchButton.addEventListener(‘click’, () => {
lookForPokemon(searchInput.value)
})

searchInput.addEventListener(‘keypress’, (e) => {
if (e.key === ‘Enter’) {
searchButton.click()
}
})

  • {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: “Poppins”, sans-serif;
    }
    body {
    background-color: #eff3ff;
    }

#card-border {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border: 14px solid #F7D02C;
border-radius: 20px
}
.container {
width: 350px;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}

#card {
display: block;
position: relative;
width: 100%;
height: 490px;
margin-top: 240px;
padding: 30px 20px;
box-shadow: 0 20px 30px rgba(0, 0, 0, 0.15);
border-radius: 20px;
background-image: url(‘https://i.imgflip.com/4u047e.png’);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}

#card .img {
display: block;
width: 180px;
max-height: 200px;
position: relative;
margin: 20px auto;
}

#search-button, #search-input {
display: block;
padding: 15px 60px;
font-size: 18px;
background-color: #101010;
color: #ffffff;
position: relative;
margin: 30px auto;
border: none;
border-radius: 5px;
}

#search-button:hover {
cursor: pointer;
background-color: #202020;
transform: translate(2px, 5px)
}

#search-input:focus {
border: 2px solid #FF10
}

#search-input {
text-align: center
}

tbody td {
background-color: rgba(255,255,255,0);
transition: all 0.2s linear;
transition-delay: 0.3s, 0s;
opacity: 0.6;
}
tbody tr:hover td {
background-color: rgba(255,255,255,1);
transition-delay: 0s, 0s;
opacity: 1;
font-size: 1.5em;
}

td {
transform-origin: center left;
transition-property: transform;
transition-duration: 0.4s;
transition-timing-function: ease-in-out;
}
tr:hover td {
transform: scale(1.1);
}

thead th {
text-shadow: 1px 2px white
}

table {
width: 90%;
margin: 0 5%;
text-align: center;
}
th, td {
padding: 0.2em;
text-align: left
}

.tablescroll {
position: relative;
top: 230px;
height: 150px;
overflow: auto;
overflow-x: hidden;
}

.pokemonname {
display: flex;
gap: 10px;
position: absolute;
justify-content: center;
left: 80px;
top: 17px;
/* background-color: #F7D02C; /
width: 170px;
border-radius: 20px 0px 20px 0px;
}
.weight {
display: flex;
gap: 10px;
position: absolute;
justify-content: center;
left: 21px;
top: 415px;
/
background-color: #F7D02C; /
width: 150px;
border-radius: 20px 0px 20px 0px;
}
.height {
display: flex;
gap: 10px;
position: absolute;
justify-content: center;
left: 21px;
top: 445px;
/
background-color: #F7D02C; */
width: 135px;
border-radius: 20px 0px 20px 0px;
}

.parent {
position: absolute;
left: 180px;
top: 415px;
/* background-color: #F7D02C; */
width: 120px;
height: 50px;
border-radius: 10px 0px 10px 0px;
transform: skew(-40deg);
}

.types {
display: flex;
flex-direction: column;
position: absolute;
justify-content:center;
place-items: center;
left: 180px;
top: 415px;
width: 120px;
height: 50px;
}

.imgcontainer {
display: flex;
position: absolute;
justify-content: center;
place-items: center;
width: 290px;
height: 195px;
left: 31px;
top: 49px;
}

.pokemonimage {
position: relative;
width: 90%;
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0

Challenge Information:

Build a Pokémon Search App Project - Build a Pokémon Search App

You need to paste your code in here using the following method so we can see it properly and copy/paste it for our own testing. Be sure to paste each file in here separately.

To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key. You may also be able to use Ctrl+e to automatically give you the triple back ticks while you are typing in the this editor and the cursor is on a line by itself. Alternatively, with the cursor on a line by itself, you can use the </> button above the editor to add the triple back ticks.

const apiUrl = 'https://pokeapi-proxy.freecodecamp.rocks/api/pokemon'

const pokemonImgProxi = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Pok%C3%A9mon_Trading_Card_Game_logo.svg/1200px-Pok%C3%A9mon_Trading_Card_Game_logo.svg.png'

const colours = {
	normal: '#A8A77A',
	fire: '#EE8130',
	water: '#6390F0',
	electric: '#F7D02C',
	grass: '#7AC74C',
	ice: '#96D9D6',
	fighting: '#C22E28',
	poison: '#A33EA1',
	ground: '#E2BF65',
	flying: '#A98FF3',
	psychic: '#F95587',
	bug: '#A6B91A',
	rock: '#B6A136',
	ghost: '#735797',
	dragon: '#6F35FC',
	dark: '#705746',
	steel: '#B7B7CE',
	fairy: '#D685AD',
};

const backgrNameId = document.getElementsByClassName('pokemonname')

const searchInput = document.getElementById('search-input')

const pokemonName = document.getElementById('pokemon-name')

const pokemonImg = document.getElementById('imgcontainer')

const pokemonId = document.getElementById('pokemon-id')

const pokemonWeight = document.getElementById('weight')

const pokemonHeight = document.getElementById('height')

const pokemonTypes = document.getElementsByClassName('types')

const pokemonHp = document.getElementById('hp')

const pokemonAttack = document.getElementById('attack')

const pokemonDefense = document.getElementById('defense')

const pokemonSpecialAttack = document.getElementById('special-attack')

const pokemonSpecialDefense = document.getElementById('special-defense')

const pokemonSpeed = document.getElementById('speed')

const cardBorder = document.getElementById('card-border')

const searchButton = document.getElementById('search-button')

pokemonImg.innerHTML = `<img id='sprite' src='${pokemonImgProxi}' alt='pokemon-image' class='pokemonimage'/>`

const convertHexToRgb = (hex) => {
	hex = hex.slice(1)
	return [Number.parseInt(hex.slice(0,2), 16), Number.parseInt(hex.slice(2,4), 16), Number.parseInt(hex.slice(4,6), 16)]
}

const contrastColor = (color) => {
	let luminance = Number.parseFloat((0.299*color[0] + 0.587*color[1] + 0.114*color[2])/255)
	return luminance>0.5 ? [0,0,0] : [255,255,255]
}

const lookForPokemon = async (searchStr) => {
  if (searchStr) {
    let searchResult = await getAllPokemons(apiUrl)
    searchResult = searchResult.results.filter(({name, id}) => {return name == searchStr.toLowerCase() || id == searchStr})
  if (searchResult.length == 1) {
    showPokemon(searchResult[0].url.replace(/http/, 'https').slice(0,-1))
    } else if (searchResult.length == 0) {
			alert('Pokémon not found')
		}
  }
}

const getAllPokemons = async (url) => {

  const response = await fetch(url)

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  } else {
    return await response.json()
  }
}

const showPokemon = async (url) => {
  const pokemon = await getAllPokemons(url)
	let backColor=convertHexToRgb(colours['electric'])
	let textColor=contrastColor(backColor)
	if (pokemon.types[0].type.name) {
		backColor=convertHexToRgb(colours[pokemon.types[0].type.name])
	}
	let backColorHTML='rgb(' + backColor.join(', ') + ')'
	let textColorHTML='rgb(' + textColor.join(', ') + ')'
	for (let p=0; p<=3; p++) {
		backgrNameId[p].style.backgroundColor = backColorHTML
		backgrNameId[p].style.color = textColorHTML
	}
	cardBorder.style.borderColor = backColorHTML
	pokemonName.innerText = pokemon.name.toUpperCase()
	pokemonId.innerText = pokemon.id
	pokemonWeight.innerText = 'Weight: ' + pokemon.weight
	pokemonHeight.innerText = 'Height: ' + pokemon.height
	pokemonTypes[0].innerHTML = ''
pokemonImg.innerHTML = ''
	for (let typeName of pokemon.types) {
		pokemonTypes[0].innerHTML += '<h4>' + typeName.type.name.toUpperCase() + '</h4>'
	}
	pokemonHp.innerText = pokemon.stats[0].base_stat
	pokemonAttack.innerText = pokemon.stats[1].base_stat
	pokemonDefense.innerText = pokemon.stats[2].base_stat
	pokemonSpecialAttack.innerText = pokemon.stats[3].base_stat
	pokemonSpecialDefense.innerText = pokemon.stats[4].base_stat
	pokemonSpeed.innerText = pokemon.stats[5].base_stat
	pokemonImg.innerHTML = `<img id="sprite" src="${pokemon.sprites.front_default}" alt="pokemon-image" class="pokemonimage" />`
}

searchButton.addEventListener('click', () => {
   lookForPokemon(searchInput.value)
})

searchInput.addEventListener('keypress', (e) => {
	if (e.key === 'Enter') {
		searchButton.click()
	}
})
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #eff3ff;
}

#card-border {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  border: 14px solid #F7D02C;
  border-radius: 20px
}
.container {
  width: 350px;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

#card {
    display: block;
    position: relative;
    width: 100%;
    height: 490px;
    margin-top: 240px;
    padding: 30px 20px;
    box-shadow: 0 20px 30px rgba(0, 0, 0, 0.15);
    border-radius: 20px;
    background-image: url('https://i.imgflip.com/4u047e.png');
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
}

#card .img {
    display: block;
    width: 180px;
    max-height: 200px;
    position: relative;
    margin: 20px auto;
}


#search-button, #search-input {
    display: block;
    padding: 15px 60px;
    font-size: 18px;
    background-color: #101010;
    color: #ffffff;
    position: relative;
    margin: 30px auto;
    border: none;
    border-radius: 5px;
  }

  #search-button:hover {
    cursor: pointer;
    background-color: #202020;
    transform: translate(2px, 5px)
  }

  #search-input:focus {
    border: 2px solid #FF10
  }

  #search-input {
    text-align: center
  }

tbody td {
  background-color: rgba(255,255,255,0);
  transition: all 0.2s linear; 
  transition-delay: 0.3s, 0s;
  opacity: 0.6;
}
tbody tr:hover td {
  background-color: rgba(255,255,255,1);
  transition-delay: 0s, 0s;
  opacity: 1;
  font-size: 1.5em;
}

td {
  transform-origin: center left;
  transition-property: transform;
  transition-duration: 0.4s;
  transition-timing-function: ease-in-out;
}
tr:hover td {
  transform: scale(1.1);
}

thead th {
  text-shadow: 1px 2px white
}

table {
  width: 90%;
  margin: 0 5%;
  text-align: center;
}
th, td {
  padding: 0.2em;
  text-align: left
}

.tablescroll {
  position: relative;
  top: 230px;
  height: 150px;
  overflow: auto;
  overflow-x: hidden;
}

.pokemonname {
  display: flex;
  gap: 10px;
  position: absolute;
  justify-content: center;
  left: 80px;
  top: 17px;
  /* background-color: #F7D02C; */
  width: 170px;
  border-radius: 20px 0px 20px 0px;
}
.weight {
  display: flex;
  gap: 10px;
  position: absolute;
  justify-content: center;
  left: 21px;
  top: 415px;
  /* background-color: #F7D02C; */
  width: 150px;
  border-radius: 20px 0px 20px 0px;
}
.height {
  display: flex;
  gap: 10px;
  position: absolute;
  justify-content: center;
  left: 21px;
  top: 445px;
  /* background-color: #F7D02C; */
  width: 135px;
  border-radius: 20px 0px 20px 0px;
}

.parent {
  position: absolute;
  left: 180px;
  top: 415px;
  /* background-color: #F7D02C; */
  width: 120px;
  height: 50px;
  border-radius: 10px 0px 10px 0px;
  transform: skew(-40deg);
}

.types {
  display: flex;
  flex-direction: column;
  position: absolute;
  justify-content:center;
  place-items: center;
  left: 180px;
  top: 415px;
  width: 120px;
  height: 50px;
}


.imgcontainer {
  display: flex;
  position: absolute;
  justify-content: center;
  place-items: center;
  width: 290px;
  height: 195px;
  left: 31px;
  top: 49px;
}

.pokemonimage {
  position: relative;
  width: 90%;
}
<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta charset='UTF-8' />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel='stylesheet' href='styles.css' />
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet" />
    <title>Pokémon Search App</title>
  </head>
  <body>
    <main>
      <div id='container' class='container'>
        <div id='card'>
          <div id='card-border'>
          </div>
          <div id='imgcontainer' class='imgcontainer'>
            
          </div>
          <div class='pokemonname'>
            <h4 id='pokemon-name'></h4>
            <h4 id='pokemon-id'></h4>
          </div>
          <div class='tablescroll'>
            <table id='charcter' class='characteristics'>
              <thead>
                <tr>
                  <th class="header">Base</th>
                  <th class="header">Stats</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>HP</td>
                  <td id='hp'></td>
                </tr>
                <tr>
                  <td>Attack</td>
                  <td id='attack'></td>
                </tr>
                <tr>
                  <td>Defense</td>
                  <td id='defense'></td>
                </tr>
                <tr>
                  <td>Sp-l attack</td>
                  <td id='special-attack'></td>
                </tr>
                <tr>
                  <td>Sp-l defence</td>
                  <td id='special-defense'></td>
                </tr>
                <tr>
                  <td>Speed</td>
                  <td id='speed'></td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class='pokemonname weight'>
            <h4 id='weight'></h4>
          </div>
          <div class='pokemonname height'>
            <h4 id='height'></h4>
          </div>
          <div class="pokemonname parent">
          </div>
          <div class='types' id='types'>
            
          </div>
        </div>
        <input id='search-input' type='text' autocomplete="none" required />
        <button id='search-button'> search </button>
      </div>
    </main>
    <script src="script.js"></script>
  </body>
</html>

Ya, it’s as if the tests aren’t waiting long enough for the fetch to return so you can update the elements. When I run the tests, sometimes only one of them fails, and other times two or even three of them fail. It just depends on how long the fetch takes to return (I’m assuming).

I’m tempted to say this is a bug in the tests but let’s wait to see if someone else chimes in with another explanation.

1 Like

Thank you very much… I am going to take counsel of my pillow :sleeping_bed:

Increasing all the delays to 1000ms does let your code pass.

I will say the example project passes more consistently, but I did see it fail. It only has a single async function with one fetch call. So it might be the extra async function calls you have.

1 Like

still fail to pass 15th and 18th tests with my code. I will change it to have one async but, I think maybe delay stuff must consider person’s location - is it possible that API queries more time consumable for some locations?

Nailed it this way (as you have said - off with one fetch and it passes:

const apiUrl = 'https://pokeapi-proxy.freecodecamp.rocks/api/pokemon'

const pokemonImgProxi = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Pok%C3%A9mon_Trading_Card_Game_logo.svg/1200px-Pok%C3%A9mon_Trading_Card_Game_logo.svg.png'

const colours = {
	normal: '#A8A77A',
	fire: '#EE8130',
	water: '#6390F0',
	electric: '#F7D02C',
	grass: '#7AC74C',
	ice: '#96D9D6',
	fighting: '#C22E28',
	poison: '#A33EA1',
	ground: '#E2BF65',
	flying: '#A98FF3',
	psychic: '#F95587',
	bug: '#A6B91A',
	rock: '#B6A136',
	ghost: '#735797',
	dragon: '#6F35FC',
	dark: '#705746',
	steel: '#B7B7CE',
	fairy: '#D685AD',
};

const backgrNameId = document.getElementsByClassName('pokemonname')

const searchInput = document.getElementById('search-input')

const pokemonName = document.getElementById('pokemon-name')

const pokemonImg = document.getElementById('imgcontainer')

const pokemonId = document.getElementById('pokemon-id')

const pokemonWeight = document.getElementById('weight')

const pokemonHeight = document.getElementById('height')

const pokemonTypes = document.getElementsByClassName('types')

const pokemonHp = document.getElementById('hp')

const pokemonAttack = document.getElementById('attack')

const pokemonDefense = document.getElementById('defense')

const pokemonSpecialAttack = document.getElementById('special-attack')

const pokemonSpecialDefense = document.getElementById('special-defense')

const pokemonSpeed = document.getElementById('speed')

const cardBorder = document.getElementById('card-border')

const searchButton = document.getElementById('search-button')

pokemonImg.innerHTML = `<img id='sprite' src='${pokemonImgProxi}' alt='pokemon-image' class='pokemonimage'/>`

const convertHexToRgb = (hex) => {
	hex = hex.slice(1)
	return [Number.parseInt(hex.slice(0,2), 16), Number.parseInt(hex.slice(2,4), 16), Number.parseInt(hex.slice(4,6), 16)]
}

const contrastColor = (color) => {
	let luminance = Number.parseFloat((0.299*color[0] + 0.587*color[1] + 0.114*color[2])/255)
	return luminance>0.5 ? [0, 0, 0] : [255, 255, 255]
}

const lookForPokemon = async (searchStr) => {
  if (searchStr) {
    const searchResult = await getAllPokemons(`https://pokeapi-proxy.freecodecamp.rocks/api/pokemon/${searchStr.toLowerCase()}`)
		showPokemon(searchResult)
		
    // searchResult = searchResult.results.filter(({name, id}) => {return name == searchStr.toLowerCase() || id == searchStr})
		// if (searchResult.length == 1) {
		// 	showPokemon(searchResult[0].url.replace(/http/, 'https').slice(0,-1))
		// } else if (searchResult.length == 0) {
		// 	alert('Pokémon not found')
		// }
		
  }
}

const getAllPokemons = async (url) => {

  const response = await fetch(url)

  if (!response.ok) {
    alert('Pokémon not found');
  } else {
		const result = await response.json()
    return result
  }
}

const showPokemon = (pokemon) => {
	let backColor=convertHexToRgb(colours['electric'])
	let textColor=contrastColor(backColor)
	if (pokemon.types[0].type.name) {
		backColor=convertHexToRgb(colours[pokemon.types[0].type.name])
	}
	let backColorHTML='rgb(' + backColor.join(', ') + ')'
	let textColorHTML='rgb(' + textColor.join(', ') + ')'
	for (let p=0; p<=3; p++) {
		backgrNameId[p].style.backgroundColor = backColorHTML
		backgrNameId[p].style.color = textColorHTML
	}
	cardBorder.style.borderColor = backColorHTML
	pokemonName.innerText = pokemon.name.toUpperCase()
	pokemonId.innerText = pokemon.id
	pokemonWeight.innerText = 'Weight: ' + pokemon.weight
	pokemonHeight.innerText = 'Height: ' + pokemon.height
	pokemonTypes[0].innerHTML = ''
pokemonImg.innerHTML = ''
	for (let typeName of pokemon.types) {
		pokemonTypes[0].innerHTML += '<h4>' + typeName.type.name.toUpperCase() + '</h4>'
	}
	pokemonHp.innerText = pokemon.stats[0].base_stat
	pokemonAttack.innerText = pokemon.stats[1].base_stat
	pokemonDefense.innerText = pokemon.stats[2].base_stat
	pokemonSpecialAttack.innerText = pokemon.stats[3].base_stat
	pokemonSpecialDefense.innerText = pokemon.stats[4].base_stat
	pokemonSpeed.innerText = pokemon.stats[5].base_stat
	pokemonImg.innerHTML = `<img id="sprite" src="${pokemon.sprites.front_default}" alt="pokemon-image" class="pokemonimage" />`
}

searchButton.addEventListener('click', () => {
   lookForPokemon(searchInput.value)
})

searchInput.addEventListener('keypress', (e) => {
	if (e.key === 'Enter') {
		searchButton.click()
	}
})

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.