By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – The pokédex that I can’t continue [closed]
JavaScript

Javascript – The pokédex that I can’t continue [closed]

Admin
Last updated: 2023/12/20 at 4:36 PM
Admin
Share
6 Min Read
The pokédex that I can't continue [closed]

Problem:

Closed. This question needs details or clarity. It is not currently accepting answers.


Want to improve this question? Add details and clarify the problem by editing this post.

Contents
Problem:Solution:

Closed 2 months ago.

The community reviewed whether to reopen this question 2 months ago and left it closed:

Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.


Improve this question

I am a beginner. I’m trying to display information about my Pokemon when I click on them.

Once I click on Pikachu, for example, I would like its index, image front, image back, and name.

Where is the problem? Because I have already created a click event, but it’s not working.

My code does not work as expected because when clicked, nothing is displayed. So I should have this information: index, image front, image back, and name.

I just opened my console (I hadn’t done it before, thank you for letting me know) and it shows me this:

index.html:112 Uncaught (in promise) ReferenceError: ceil is not defined
     at index.html:112:9

In the debugger it shows me the same thing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokédex</title>
</head>
<body>
    <div id='grid'>

    </div>
    <div id="grid2"></div>
</body>
</html>

<style>
    #grid2
    {
        display: none;
    }
    .item{
        display: flex;
        flex-direction: column;
        align-items: center;
        border: solid;
    }
    #grid{
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 10px;
    }
</style>
<script>
    //Crée une constante grid qui stocke l’élément HTML avec l’ID grid. Cet élément est utilisé plus tard pour ajouter des éléments à la page.
    const grid = document.getElementById('grid')

    //Envoie une requête à l’API PokeAPI pour récupérer les 151 premiers Pokémon. La méthode fetch() renvoie une promesse qui sera résolue lorsque la réponse sera reçue.
    fetch('https://pokeapi.co/api/v2/pokemon?limit=151')
    //Utilise la méthode then() pour extraire les données JSON de la réponse de l’API. La méthode json() renvoie également une promesse.
    .then(response => response.json())
    //Utilise la méthode then() pour accéder aux données JSON extraites de la réponse de l’API.
    .then(data => {
        //Crée une constante results qui stocke les résultats de la requête API sous forme d’un tableau d’objets Pokémon.
        const results = data.results
        // Utilise la méthode forEach() pour parcourir chaque objet Pokémon dans le tableau results. La méthode forEach() prend une fonction de rappel qui est appelée pour chaque élément du tableau.
        results.forEach((pokemon, index) => {
            // Crée un nouvel élément HTML <div> qui sera utilisé pour afficher les informations sur chaque Pokémon.
            const ceil = document.createElement('div')
            // Ajoute la classe item au nouvel élément HTML <div>.
            ceil.classList.add('item')
            // Crée une constante pokemonNumber qui stocke le numéro du Pokémon actuel dans le tableau, en incrémentant l’index de 1.
            const pokemonNumber = ++index

            // Crée un nouvel élément HTML <img> qui sera utilisé pour afficher l’image du Pokémon.
            const img = document.createElement('img')
            //Définit l’attribut src de l’élément <img> créé précédemment en utilisant le numéro du Pokémon actuel dans le tableau.
            img.src=`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonNumber}.png`
            // Crée un nouvel élément HTML <div> qui sera utilisé pour afficher le nom du Pokémon.
            const name = document.createElement('div')
            // Crée une constante pokemonName qui stocke le nom du Pokémon actuel dans le tableau.
            const pokemonName = pokemon.name
            // Définit le texte interne de l’élément <div> créé précédemment en utilisant le nom du Pokémon actuel dans le tableau.
            name.innerText = pokemonName
            // Ajoute l’élément <img> créé précédemment à l’élément <div> créé précédemment.
            ceil.appendChild(img)
            // Ajoute l’élément <div> créé précédemment contenant le nom du Pokémon à l’élément <div> créé précédemment.
            ceil.appendChild(name)
            // Ajoute l’élément <div> créé précédemment contenant toutes les informations sur le Pokémon à la page HTML, en l’ajoutant comme enfant de l’élément avec l’ID 'grid'.
            grid.appendChild(ceil)
        })
        

        // Ajoute un gestionnaire d'événements onclick à chaque élément de la grille
        ceil.onclick = function() {
            fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonNumber}`)
            .then(response => response.json())
            .then(data => {
                console.log(`Index: ${pokemonNumber}`)
                console.log(`Image Front: ${data.sprites.front_default}`)
                console.log(`Image Back: ${data.sprites.back_default}`)
                console.log(`Name: ${data.name}`)
            })
        }
    }) 
</script>

Here is the site where I get the APIs : https://pokeapi.co/

Solution:

The ceil.onclick = function() is currently outside the result.forEach, therefore the ceil is not defined error is thrown.

Move that assignment inside the loop, before you append the new ceil element

const grid = document.getElementById('grid')

fetch('https://pokeapi.co/api/v2/pokemon?limit=151')
.then(response => response.json())
.then(data => {
    const results = data.results
    results.forEach((pokemon, index) => {
        const ceil = document.createElement('div')
        ceil.classList.add('item')
        const pokemonNumber = ++index

        ceil.onclick = function() {
            fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonNumber}`)
            .then(response => response.json())
            .then(data => {
                console.log(`Index: ${pokemonNumber}`)
                console.log(`Image Front: ${data.sprites.front_default}`)
                console.log(`Image Back: ${data.sprites.back_default}`)
                console.log(`Name: ${data.name}`)
            })
        }
        
        const img = document.createElement('img')
        //Définit l’attribut src de l’élément <img> créé précédemment en utilisant le numéro du Pokémon actuel dans le tableau.
        img.src=`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonNumber}.png`
        const name = document.createElement('div')
        const pokemonName = pokemon.name
        name.innerText = pokemonName
        ceil.appendChild(img)
        ceil.appendChild(name)
        grid.appendChild(ceil)
    })


}) 
#grid2 {
    display: none;
}
.item{
    display: flex;
    flex-direction: column;
    align-items: center;
    border: solid;
}
#grid{
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
}
<div id='grid'>

</div>
<div id="grid2"></div>

Expand snippet

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Add multiple range filters on Jquery Data table Javascript – Add multiple range filters on Jquery Data table
Next Article How to make the text under my picture change when hovering over the picture (html, css, javascript) Javascript – How to make the text under my picture change when hovering over the picture (html, css, javascript)
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?