Making A Custom ToolTip

Recently, I had to make a custom tooltip when we hover over icons. I didn’t wanted to insert lot of HTML, laziness most probably but also the amount of markup that the browser would have to render and somehow did not want to use an outside plugin, so I had to come up with something which would float around it while knowing which element is being hovered on.

Trying and testing the easiest way to make one code for all sides of tooltips(top,right,bottom,left), I came up with this:

I attached an event on an attribute data-tooltip which can be given a value top,right, bottom or left as data-tooltip='top' according to how you want the tooltip to appear. I have given the information to show in tooltip in title but that can interfere with our custom tooltip and it can look annoying but you can change titleto data-title and it will still work.

I think there would be accessibility issue if you remove title, but I dont know exactly about it because I see that people also use data-title or data-aria-title to replace the ugly design of browser tooltip.

jQuery’s .offset() is what gives us where the element hovered on is and gives us topand left of that element.

left = $(this).offset().left
top = $(this).offset().top

Manipulate that accordingly and you will be able to put that tooltip wherever you want.

Now, by just adding data-tooltip='top' and data-title='show info' to any HTML element you can show a tooltip for that element.

Be the first to comment

Leave a Reply

Your email address will not be published.


*