Simple tooltip in jQuery

In this post, I have attempted to create custom jQuery code to show the tooltip on mouseover event.

Create a DIV element

<div class="tooltip" id="toolt" style="display: none;"></div>

Ceate a div element and name the ID as “toolt”(not necessarily same name) and initially hide the division by giving style=”display:none;” option

CSS for the element:

.tooltip{
  border:1px dashed #0000FF;
  padding-left:10px;
  padding:5px;
  width:100px;
  background-color:#CCFFFF;
  position:absolute;
  opacity:0.9;
  font-family:Geneva;
  font-weight:bold;
  -moz-box-shadow: 0 0 13px #888;
  -webkit-box-shadow: 0 0 13px #888;
  box-shadow: 0 0 13px #888;
  -moz-border-radius:3px;
}

Note that i have called the css through .tooltip class in the division which is supposed to be used for tooltip on hover.

jQuery to show tooltip:

function show(id,txt){
    $(id).mouseover(function(e){
    var offsetsLeft = $(window).scrollLeft();
    var offsetsTop = $(window).scrollTop();
    leftpos = parseInt(offsetsLeft + (e.pageX)) + 'px';
    toppos = parseFloat(offsetsTop + (e.pageY)) + 'px';
    $('#toolt').css({'top':toppos,'left':leftpos});
    document.getElementById("toolt").innerHTML=txt;
    $('#toolt').show();
});

$(id).mouseout(function(e){
    $('#toolt').hide();
    e.stopPropagation();
});
}

First , we need to pass the parameter to the function “show()”(see below to see how it is initialized), the first parameter should be DOM object type like a,p,span,div etc; the second parameter should be the content that will be displayed in the tooltip.
Next we shall calculate the mousepointer coordinates and call the tooltip division on that particular division.The first part of the function will do that trick.
Later, when mouse is taken off we will hide that division again.

Initializing the tooltip:

<a href="javascript:void(0);" onmouseover="show('p','This is a tooltip content')">Hover Here</a>

If you need to call a tooltip for the ‘p’ tag, then you can use the above method to initialize the tooltip. Dont forget to pass the DOM object in the first parameter and remember your DOM object will be your first parameter.

Let us know in comment what you think of this post.

Hit Like if this article was useful to you!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Leave a Reply

Your email address will not be published. Required fields are marked *