#Why am I getting "PointerEvent" when I click an li from a for loop and event listener?

18 messages · Page 1 of 1 (latest)

rotund grotto
#

I want to console.log the element I clicked, the element I clicked is inside the array 'listLi'. Why is the code I have not working? How would I get what I want?

#

I am not getting an error, but I am not getting what I want, I want to get the html itself

azure laurel
#

then in your anonymous closure you're creating, you need to capture the element you're adding the event listener to, or listLi[i]

#

as you can see, the argument passed to your anonymous function is the PointerEvent

rotund grotto
azure laurel
#

are you sure?

rotund grotto
#

I am getting undefined

#

not PointerEvent

azure laurel
#

but also, i think i will change, so you need to capture that value

azure laurel
rotund grotto
azure laurel
#

the problem is that by the time the event listener fires, i has changed. and then probably listLi has changed too

rotund grotto
#

I understand the logic of the word 'capture', but I am not sure how I would do that

azure laurel
#

it's been a while since I did this, but one way would be with a .bind() call on your anonymous function

#

something like:

const handler = (function(event) {
  console.log(this);
}).bind(listLi[i]);
listLi[i].addEventListener("click", handler);
rotund grotto
glacial urchin
glacial urchin