Say no to jquery for tooltip

say-no-jq-tooltip
Tooltip – A common Graphical User Interface(GUI) element. This tooltip is a helper text that will appear when the user hovers a mouse pointer above HTML element, without clicking it. A tooltip contains information about an item.

You may have created many tooltips using jquery. But now in this demo, we are going to discuss an alternative way to create a tooltip using HTML and CSS.

The reason behind choosing HTML, CSS

In jquery, to display a tooltip we will use functions like onmouseover, onmouseenter and more. But in CSS we can use data attribute(data-message) and pseudo elements such as :after, :before to display a tooltip.

HTML Markup

First create HTML Element with class = “tooltip” and set tooltip message in data attribute as data-messsage = “Your help text…”

CSS

.tooltip:before{
content: attr(data-message);
}

Add tooltip text in :before pseudo element using content: attr(data-message);

Now add styles such as background color, font style, padding to :before pseudo element.

.tooltip:before{
content: attr(data-message);
padding: 10px 20px;
background: #111;
color: #fff;
white-space: nowrap;
font-size: 12px;
border-radius: 3px;
position: absolute;
opacity: 0;
transform: translate3d(-50%, 0px, 0);
margin-bottom: 7px;
transform-origin: top;
left: 50%;
bottom: 100%;
}

By above styles, placed tooltip above the hover element with opacity:0. On hover element, Set opacity as 1.

.tooltip:hover:before{
opacity: 1;
}

Now you can add transition effect to the tooltip.

.tooltip:before{
transform: translate3d(-50%, 0px, 0);
transition: 0.18s all ease-out;
opacity: 0;
}

.tooltip:hover:before{
transform: translate3d(-50%, -10px, 0);
opacity: 1;
}

and you can show tooltip in various places such as top, right, bottom, left.

You may also like