'.mouseover in Javascript does not work when set to a function, but returns normally when using a new function

currently I'm using a for loop to iterate over some tags, and when I try to alter the

tags .mouseover in JS, it returns null.

let htmlElements = document.getElementsByTagName("a");
for (let i = 0; i < 22; i++) {
  for (let j = 0; j < 20; j++) {
    htmlElements[i * 20 + j].onmouseover = onTileHovered(j, i, this);
 }
}

If I console.log, it prints out null.

A solution for this is putting set it and make the function there.

let htmlElements = document.getElementsByTagName("a");`
for (let i = 0; i < 22; i++) {
    for (let j = 0; j < 20; j++) {
      htmlElements[i * 20 + j].onmouseover = function () {
      // function stuff
      };
    }
}

This works, however, I'm worried that this would be making multiple copies of the function which would be pretty inefficient, and was wondering why the other way doesn't work.



Solution 1:[1]

What you're doing is perfectly fine. Adding 400 event listeners will have no visible impact at all on an application on modern devices, even on potato-level phones. Computers can handle repetitive tasks of much higher intensity.

If you were adding enough listeners that it was an issue to consider, then an approach would be to turn the elements into an array, and whenever a container of all those <a>s is moseovered, check the index of the element in the array.

const aContainer = document.querySelector('.container'); // replace this with appropriate selector
const anchors = [...aContainer.querySelectorAll('a')];
aContainer.addEventListener('mouseover', (e) => {
  const { target } = e;
  const a = target.closest('a');
  if (!a) return;
  const index = anchors.indexOf(a);
  // do stuff with the clicked anchor and the index
  // modulo can be used to find i and j, if needed
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance