I'm trying to locate which element newly rendered is under mouse pointer. (*)
Here is my code:
btn.addEventListener('click', function () {
btn.remove();
for (let i = 0; i < 10; i++) {
lst.appendChild(document.createElement('li')).textContent = 'Element ' + i;
}
requestAnimationFrame(function () { requestAnimationFrame(function () {
const chosen = document.querySelector('li:hover');
alert(chosen && 'Your mouse on ' + chosen.textContent); // do something more with chosen
}); });
});
#btn { width: 200px; height: 200px; }
#lst { width: 200px; line-height: 20px; display: block; padding: 0; }
#lst li { display: block; height: 20px; width: 200px; overflow: hidden; }
#lst li:hover { background: #ccc; }
<button id=btn>Click Me</button>
<ul id=lst><ul>
I'm confused that I need 2 requestAnimationFrame
to make my code execute correctly. Removing one raf, the alert will show null
instead.
The code also seems ugly to me. How to implement it more elegantly?
In case anyone care about: I'm running my code on Firefox. And the code, as a part of my Firefox extension, only need to target to Firefox 60+.
(*): The story behind may be more complex. But to keep it simple...