Recreating UI of popular websites is fun, today we are going to code the Wikipedia's tooltip !
If you prefer to watch the video version it's right here :
But first ...
What is a tooltip ?
A Tooltip is usually some context displayed by hovering a link, a button or an icon.
Let's do it, step by step.
1. Create the tooltip and the links.
The links :
<span class="tooltip"><a href="#">Tooltip1</a></span>
<span class="tooltip"><a href="#">Tooltip2</a></span>
<span class="tooltip"><a href="#">Tooltip3</a></span>
The tooltip :
<div class="tooltip-container">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero tenetur non laborum dolorem laboriosam quo quibusdam assumenda dolores eveniet. Ipsum?
</div>
Style it, with position absolute, to make it easyer to place.
.tooltip-container {
width: 425px;
min-height: 200px;
padding: 15px;
font-size: 25px;
background: white;
box-shadow: 0 30px 90px -20px rgba(0,0,0,0.3);
position: absolute;
z-index: 100;
display: none;
opacity: 0;
}
.fade-in {
display: block;
animation: fade 0.2s linear forwards;
}
@keyframes fade {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
Notice the lovely animation, to display from none to block and then animate from opacity 0 to 1 ! ♥
2 Animate with JavaScript.
Take all the links, and the tooltip container.
const tooltips= Array.from(document.querySelectorAll(".tooltip"));
const tooltipContainer = document.querySelector(".tooltip-container");
Listen to mouseenter and mouseout on every link and place the tooltip where the mouse is.
tooltips.forEach((tooltip) => {
tooltip.addEventListener("mouseenter", (e) => {
tooltipContainer.classList.add("fade-in");
tooltipContainer.style.left = `${e.pageX}px`;
tooltipContainer.style.top = `${e.pageY}px`;
});
tooltip.addEventListener("mouseout", () => {
tooltipContainer.classList.remove("fade-in");
});
});
Hurray, we made it !
If you want to add custom text for each link to the tooltip, I'm showing it in the video, I don't want to make too long article.
Source code, with all the shiny CSS is right here :
https://codepen.io/Ziratsu/pen/ExgEwOw
Come and take a look at my brand new Youtube channel :
https://www.youtube.com/channel/UCiukrDWz1wqlHAvIdqgqmQg
Be the pioneer that follows me uh ? 😎
See you next time for some quick and polished tutorials !
Discussion (3)
This is the source code for the actual pop-ups feature on Wikipedia. :)
Yep !
But wanted to show how to do it without external library :)
Agreed