Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

103
Vistas
A Function that’s dedicated to adding the event listener to the newly created button

I'm trying to create a function that is dedicated to adding the event listener to the newly created button.

I'm currently taking a course and I can't seem to understand this part:

"Optional (Advanced): You may choose to have another function that’s dedicated to adding the event listener to the newly created button rather than including the code inside the addListItem() function. If you do so, you’ll have to pass two parameters to the new function—the first is the variable referring to the button (to add the event listener to it), and the second is the Pokémon object, which is necessary to call showDetails in the event handler from there. Finally, call that new function inside addListItem() after the button is appended to the DOM."

Here is a snippet of what I came up with:

 function eventListener(button, pokemon) {
    button.addEventListener("click", function () {
      showDetails(pokemon);
    });
  }

I recommend checking out the full code: https://codesandbox.io/s/event-listener-lm16im

8 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

All that function is doing is taking reference of a button and data to display, add 'click' event listener on that button and call showDetails() function when that button is clicked.

Here, I have created demo for you to understand how it works

https://jsfiddle.net/6jhmaz8x/1/

HTML file

<html>
  <body>
    <button id="newButton">
      Create new button
    </button>
    <div id="container">
      
    </div>
  </body>
</html>

JS File:

function eventListener(button, pokemon) {
  button.addEventListener("click", function () {
    showDetails(pokemon);
  });
}
  
function showDetails(pokemon){
    console.log(pokemon)
}

window.addEventListener('DOMContentLoaded', (event) => {
    document.getElementById('newButton').addEventListener('click',()=>{
      let button = document.createElement('button');
      button.type = 'button';
      button.innerHTML = 'Show details';
      document.getElementById('container').appendChild(button)
      let pokemon = 'this is pokemon'
      eventListener(button,pokemon)
    })
});
8 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos