Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 76335

Why does my click event only work once when generating HTML, but works correctly when console.logging?

$
0
0

It functions how I intend to in the console, and when generating HTML, but it only works once with HTML, whereas it always works with the console. Do I need to use a loop here, and return the HTML that way? I tried map, but its not an array. Edit: Forgot the HTML, just added it.

<!DOCTYPE html>
<html>
<head>
<title>Pokedex</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1 id="main-header">Pokedex</h1>
<div id="main-container">

</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>

Javascript

const container = document.getElementById('main-container');

function getPokemon(callback) {
const xhr = new XMLHttpRequest();
const url = 'https://pokeapi.co/api/v2/pokemon/';

xhr.onload = function() {
    if(xhr.status === 200) {
        const pokemon = JSON.parse(xhr.responseText);
        container.innerHTML+=
        pokemon.results.map((poke, index)=>{ 
            return `
                <div class='cardFront'>
                    <img src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png'></img>
                    <h4>${poke.name}</h4>
                </div>
            `
        }).join('');

        callback();
    }
}
xhr.open('GET', url, true);
xhr.send();
}

function cardBack() {
const endPoint = this.lastChild.previousSibling.innerText;
const xhr = new XMLHttpRequest();

xhr.onload = function() {
    if(xhr.status === 200) {
        const details = JSON.parse(xhr.responseText); 
        container.innerHTML+= `
            <div class='backSide'>
                <h4>${details.name}</h4>
                <h4>${details.types[0].type.name}</h4>
            </div>
        `
    }
}
xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + endPoint, true);
xhr.send();
}

getPokemon(()=>{
const cardFront = document.querySelectorAll('.cardFront');
cardFront.forEach((card)=> {
    card.addEventListener('click', cardBack);
})
});

Viewing all articles
Browse latest Browse all 76335

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>