Cannot Access Array Items Inside Event Listener

I am trying to resize a selected element by dragging on one of its drag handles but I’m getting an error that pretty much says that the id of my handle is undefined.

Basically I have 8 small DIVs that surround a selected element and each handle has an id. I placed all the ids in a variable using querySelectAll then I tried to access the drag handles by their ids in event listeners inside a for loop.

At the moment the resize function is not working but if I could just make it work when I drag on one of the handles then I can get the rest to work. Please see my script.

Hi @liagapi555, this is a common gotcha: your index variable isn’t block scoped, so the event handlers eventually all try to access objHandles[objHandles.length], which is undefined. To solve this, you might…

  1. Use let instead of var as let is blocked scoped and the event handlers in each iteration all get their “own” index variables
  2. Don’t refer to the index variable at all but replace objHandles[i] with this inside the event handlers (this way you might actually pull them out of the loop altogether)
  3. Use the Array forEach method instead of a for loop, so that again the handlers get their own variables in each call. This is probably the most robust solution, plus you get each element passed directly rather than having to access it via the index

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