I have been trying to add a mouseover listener in javascript as follows:
for (var i = 0; i < classes.length; i++)
{
var elements = document.getElementsByClassName("class" + i.toString());
for (var j = 0; j < elements.length; j++) {
elements[j].addEventListener("mouseover", function(e) {
showDiv(i, e.pageX, e.pageY);
});
}
}
and showDiv is:
function showTranslationDiv(idx, x, y){
const notification = document.getElementsById('div0');
notification.innerHTML = "You are at: " + x.toString() + " " + y.toString();
notification.style.top = y.toString() + 'px';
notification.style.left = x.toString() + 'px';
notification.style.display = 'flex';
setTimeout(function () {
notification.style.display = 'none';
}, 5000);
}
classes is a list of 3 different class names (the real name is not relevant).
I encountered two problems here:
- When I use
style.top
, as you see above, it doesn't work anddiv0
didn't appear, but if I write a hard-coded top value (style.top = '400px'
for example) it's working fine. - the value of idx is always 3 for any class, it should be different for different class indices.
What is wrong with my code?