I have searched extensively for similar questions but have been unable to resolve my issue. Here, I am sharing just a single list item from my code. The task at hand is to create a span
element on the mousemove
event over the list
item, and dynamically set its left offset relative to its parent as the mouse moves. Since this is new territory for me, I have experimented quite a bit with the following code snippet:
document.querySelector("li a").addEventListener("mousemove",(event)=> {
let span;
let alreadyHasSpan = event.target.hasChildNodes().length > 1; //default length=1
if(!alreadyHasSpan) {
span = $(`<span class="a-effect"></span>`);
span.appendTo(event.target);
}
let targetLeftPos = event.target.getBoundingClientRect().left;
span.css("left",`${event.clientX-targetLeftPos}px`);
$(this).mouseleave(function () {
span.remove();
});
}, false);
a {
position: relative;
}
.a-effect {
position: absolute; left: 0;
height: 100%;
width: 2%;
background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="nav-item active">
<a href="/" class="nav-link">Product</a>
</li>
Despite the functionality of the span
moving along with the mouse cursor, it leaves behind trailing remnants:
https://i.sstatic.net/kDaCm.png
In addition to the trailing remnants, there are occasions when the span
fails to display altogether. This problem is exacerbated in the snippets provided for this question.
What could be causing these issues and how can they be rectified?