I want to add hover effect on specific part of the paragraph. but when mouse is positioned on the blank space between the lines mouseout
/ mouseleave
getting fired (space is caused by line-height
css). because of this the hover state keeps flickering. please refer the below image
When mouse positioned over blank space between the lines
What I have now:
const spans = document.querySelectorAll('span');
spans.forEach(span => {
span.addEventListener('mouseover', ($event) => {
span.setAttribute('hovered', 'true');
});
span.addEventListener('mouseout', ($event) => {
span.setAttribute('hovered', 'false');
});
});
span[hovered='true'] {
background-color: red;
color: white;
}
<p>
Nevererr is this principleasd more pertinent than when dealingasd with type, the bread and butter of Web-borne communication. A well-set paragraph of text is not supposed to wow the reader;
<span>
the wowing should be left to the idea or observation for which the paragraph is a vehicle. In fact, the perfect paragraph is unassuming to the point of near invisibility. That is not to say that the appearance of your text should have no appeal at all.
</span> On the contrary: well-balanced, comfortably read typography is a thing of beauty; it’s just not the arresting sort of beauty that might distract you from reading. asd.
</p>
EXAMPLE => stackblitz
please suggest some alternatives to make the hover state smooth.
2
Answers
This may be a bit overkill, but this is how it could be solved.
Determine the highest and lowest point of the span and check whether the mouse moves out of this area.
See the comments.
No need for the JavaScript so I commented it out as well as the related CSS. I then set up some CSS to remove the borders and padding by setting to 0 and made the line-height to just be one em.
Now if you really NEED the JavaScript as a part of some other functionality you can do that also – so I added a second example for that.
Example if you really need the JavaScript
Just some CSS change: