I’m making a nav button that when it is hovered, instead of there just being an icon there, there will also be some text to the right of it. Once the cursor leaves the button, it will go back to just displaying the icon.
HTML
<button title="Style Guide" id="style-guide" hover-text="Style Guide">
<i class="fa-solid fa-border-top-left"></i>
</button>
JAVASCRIPT
document.querySelectorAll("[hover-text]").forEach((element) => {
element.addEventListener("mouseover", () => {
element.innerText += element.getAttribute("hover-text");
})
element.addEventListener("mouseout", () => {
element.innerText = element.innerText.replace(element.getAttribute("hover-text"), "")
})
})
3
Answers
Use
innerHTML
instead.You should give
hover-text
toi
tag. So your html file should be like this:And the Javascript file:
Instead of using
element.innerText += ...
why not append an actual element to the button when hovered and on mouseout, remove the child:On
mouseover
, this code should add adiv
with a class namehover-text
and onmouseout
it should remove thediv.hover-text
element. You can change the element name by changinglet tooltip = document.createElement('div')
tolet tooltip = document.createElement('span')
or some other element name. You can also add styles and add a.hover-text {...}
and code some stylesThis will work well for simple stuff, but if you want a better tooltip, you will have to look for a better way to do that