I am looking to implement a hover effect for dynamically generated items in JavaScript. Specifically, when I hover over an icon element, I want a unique text to appear related to that icon:
for (var i = 0; i < items.length; i++) {
$('.items').append('<div class="icon' + i + '"></div>');
$('.itemInfo').append('<div class="info' + i + '">' + name + '</div>');
}
I have tried using jQuery's .hover() and .on() methods to show the info when hovering over the icon, but I encountered issues with getting the correct info displayed. I also attempted to hide the info initially and show it on hover, yet nothing appeared. Despite the debugger indicating that the function was being triggered, the correct index was not captured.
for (var i = 0; i < items.length; i++) {
$('.items').append('<div class="icon' + i + '"></div>');
$('.itemInfo').append('<div class="info' + i + '">' + name + '</div>');
$('.icon' + i).on({
mouseenter: function () { $('.itemInfo' + i).show(); },
mouseleave: function () { $('.itemInfo' + i).hide(); }
});
}
It's worth noting that the icons and info are kept separate in different divs for styling reasons. While the current structure works for a known number of items, I am unsure how to handle cases where the number of generated items is unknown. I'm contemplating whether merging the icon and info elements into a single div would be a better solution in such situations.