hoolix icon indicating copy to clipboard operation
hoolix copied to clipboard

JavaScript AddEventListener Bug with Window Object

Open codeCraft-Ritik opened this issue 8 months ago • 0 comments

Summary:

The addEventOnElem function (lines 9-17) checks if elem.length > 1 to determine if it's an array-like object. However, on line 64, it's called with the window object: addEventOnElem(window, "scroll", headerActive). The window object doesn't have a .length property, causing the condition to always return falsy and treat window as a single element.

While this currently works by accident (window does have addEventListener), it's improper usage and could break if the code is refactored.

Impact : Medium - Potential bug if code is refactored; violates the function's apparent design intent.

// Option 1: Fix the function to handle window explicitly
const addEventOnElem = function (elem, type, callback) {
  if (elem && typeof elem.length !== 'undefined' && elem.length > 1) {
    for (let i = 0; i < elem.length; i++) {
      elem[i].addEventListener(type, callback);
    }
  } else {
    elem.addEventListener(type, callback);
  }
}

// Option 2: Call addEventListener directly for window
window.addEventListener("scroll", headerActive);

codeCraft-Ritik avatar Mar 20 '26 14:03 codeCraft-Ritik