728

I have a div tag like this:

<div>
  <label>Name</label>
  <input type="text"/>
</div>

How can I displaying a tooltip on :hover of the div, preferably with a fade in/out effect.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
user475685
  • 8,041
  • 7
  • 26
  • 24
  • 2
    For a simple CSS+JavaScript solution, I don't think you can beat Daniel Imms' post at http://stackoverflow.com/questions/15702867/html-tooltip-position-relative-to-mouse-pointer – Rick Hitchcock Sep 08 '14 at 01:04
  • 2
    [CSS3 only](http://stackoverflow.com/a/25813336/1654265) – Andrea Ligios Nov 14 '14 at 15:08
  • http://stackoverflow.com/questions/36275678/how-to-create-a-custom-tooltip-using-css-or-how-can-we-customize-angular-ui-boos – Pooja Kedar Feb 23 '17 at 05:36
  • 1
    It's surprising no one is talking about the ARIA standard; it should be the starting point for a tooltip. See [Mozilla](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/tooltip_role). – Kalnode Dec 23 '21 at 16:06

25 Answers25

1142

For the basic tooltip, you want:

<div title="This is my tooltip">

like:

.visible {
  height: 3em;
  width: 10em;
  background: yellow;
}
<div title="This is my tooltip" class="visible"></div>

For a fancier javascript version, you can look into:

https://jqueryhouse.com/best-jquery-tooltip-plugins/

The above link gives you 25 options for tooltips.

YakovL
  • 7,557
  • 12
  • 62
  • 102
sscirrus
  • 55,407
  • 41
  • 135
  • 228
  • 2
    One thing to watch out for with a title tool tip is if the user click on the the your div the tooltip won't appear. This can be very frustrating... especially if your div looks like it should be clicked. eg: style="cursor: pointer;" – RayLoveless Mar 19 '14 at 15:07
  • 3
    @RayL It isn't standard behavior for a tooltip to be clickable - this blurs links and tooltips, preventing the user from knowing whether a highlighted word will 1) give them more information or 2) take them to another page entirely. In general, bad practice. – sscirrus Apr 14 '14 at 22:33
  • @sscirrus I agree. That's why you should NOT style your tooltips with "cursor: pointer;" (encourages clicking) which I see too often. – RayLoveless Apr 15 '14 at 17:52
  • @RayL Absolutely. From the wording in your first comment I wasn't sure whether you were encouraging it or not - glad we're all on the same page! – sscirrus Apr 16 '14 at 21:33
  • 32
    If you only want to show a tooltip for some piece of text, like "details" for some keyword or something like that, use [`...`](http://www.w3schools.com/tags/tag_abbr.asp) instead; browsers usually style this underlined with dashes / dots, indicating "there is more to tell, see my tooltip". – leemes Aug 06 '14 at 12:57
  • The jquery tooltips link is broken on the "fancier javascript version" link, you can get it here: https://jqueryui.com/tooltip/ – Michael Feb 23 '16 at 21:07
  • 7
    On Chrome, it can take a few seconds for the tooltip to appear. Kind of slow in my opinion. – Johann May 30 '17 at 06:13
  • Unfortunately, the `title` attribute simple system won't work as expected if you want to display the results of animations in it. For example, if you wanted to show the changing of the rotation or position of an animated object in a `title` attribute, you'd have to do it at sufficiently rare intervals (like once every second and such), otherwise changing the content of the attribute every couple of dozens milliseconds will result in the title tooltip not being shown at all. The CSS alternative is also restrictive in that it doesn't display things outside the browser window, so it's all a mess. – Yin Cognyto May 26 '22 at 11:36
396

It can be done with CSS only, no javascript at all

running demo

[data-tooltip]::before {
    /* needed - do not touch */
    content: attr(data-tooltip);
    position: absolute;
    opacity: 0;

    /* customizable */
    transition: all 0.15s ease;
    padding: 10px;
    color: #333;
    border-radius: 10px;
    box-shadow: 2px 2px 1px silver;
}

[data-tooltip]:hover::before {
    /* needed - do not touch */
    opacity: 1;

    /* customizable */
    background: yellow;
    margin-top: -50px;
    margin-left: 20px;
}

[data-tooltip]:not([data-tooltip-persistent])::before {
    pointer-events: none;
}

/* FOR TEST PURPOSES ONLY */
div {
    border: 1px solid silver;
    background: #ddd;
    margin: 20px;
    padding: 10px;
}
<div>Standard div, no tooltip here</div>


<div data-tooltip="Hi, I'm a tooltip. Pretty easy uh ? ;)">Div with standard tooltip. Hover me to see the tooltip.
    <br/>Hovering the tooltip doesn't matter:
    <br/>if you hover out of my boundaries, the tooltip will disappear.</div>


<div data-tooltip="Hi, I'm a persistent tooltip. I won't disappear when hovering me even if out of my parent boundaries. I'll also prevent other tooltips to fire :)" data-tooltip-persistent="foo">Div with persistent tooltip. Hover me to see the tooltip.
    <br/>The tooltip won't expire until you hover on me OR it.</div>
  1. Apply a custom HTML attribute, eg. data-tooltip="bla bla" to your object (div or whatever):

    <div data-tooltip="bla bla">
        something here
    </div>
    
  2. Define the ::before pseudoelement of each [data-tooltip] object to be transparent, absolutely positioned and with data-tooltip="" value as content:

    [data-tooltip]::before {
        position : absolute;
        content : attr(data-tooltip);
        opacity : 0;
    }
    
  3. Define :hover::before hovering state of each [data-tooltip] to make it visible:

    [data-tooltip]:hover::before {
        opacity : 1;
    }
    
  4. Apply your styles (color, size, position etc) to the tooltip object; end of the story. In the demo I've defined another rule to specify if the tooltip must disappear when hovering over it but outside of the parent, with another custom attribute, data-tooltip-persistent, and a simple rule:

    [data-tooltip]:not([data-tooltip-persistent])::before {
        pointer-events: none;
    }
    

Note 1: The browser coverage for this is very wide, but consider using a javascript fallback (if needed) for old IE.

Note 2: an enhancement might be adding a bit of javascript to calculate the mouse position and add it to the pseudo elements, by changing a class applied to it.

Kartik Soneji
  • 1,066
  • 1
  • 13
  • 25
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • What is old IE here? IE 7? IE 8? – Quentin Pradet Aug 27 '15 at 11:49
  • 1
    @AndreaLigios Could this be changed, so that the tooltip is scaled to 1x1px when not shown and that pixel should be somewhere at 0,0 coordinates of the text? Currently there is a glitch in the demo: When putting the mouse at the area below the third div in the demo, the tooltip starts appearing, but then is moving away from the mouse-pointer, and so goes back to it's starting position, which again trickers the appearing. That's happening impressivly fast and shows a flickering. – John Mar 17 '16 at 14:47
  • Ahah, nice catch, you're the first one noticing it (including me). This is just a kickoff example, however, you should customize your code with the desired behavior and optimization (eg. making it start at the mouse position, or moving left / right according to the viewport space available, eg. if you are close to boundaries). BTW you can definitely do what you proposed, with a different effect on popup, though. OR you could go for other solutions, eg. adding a delay to the object (while not on its hovering): http://jsfiddle.net/msn9frjw/ this way the glitch is still there, but less annoying – Andrea Ligios Mar 17 '16 at 15:43
  • 2
    This is awesome! But: how can we add a line break here? It seems to ignore `
    ` and others like `\n` or `\r` as these just appear as plain text in the rest of the string. **Update:** I just noticed setting a max-width makes it automatically adjust its content and put line breaks. Really neat! (However, if someone knows an answer, I'd still appreciate that)
    – LinusGeffarth Nov 28 '17 at 11:42
  • I'm trying this and I'm getting the error of unable to bind since tooltip isn't a known property of div. I'm in Angular2 if that makes a difference. – Reverend Bubbles Feb 23 '18 at 20:24
  • Can it be done in some way that if the value of tooltip attribute is blank then no tooltip will be shown? – amitava mozumder Nov 26 '18 at 10:35
  • @amitavamozumder simply include the `tooltip=""` part in the value you inject or not ;) – Andrea Ligios Nov 26 '18 at 13:32
  • @AndreaLigios sorry I didn't get that. which value you're talking about? and in which file? – amitava mozumder Nov 27 '18 at 05:56
  • If you need to turn on or off the tooltip programmatically (no matter if coming from server side or if at runtime with javascript), instead of nulling the *value* of tooltip="", delete and recreate *the tooltip attribute itself* – Andrea Ligios Nov 27 '18 at 08:23
  • 1
    Instead of making it visible with opacity:0/1, I set the content, width, border, padding, etc. on hover. Otherwise, it will block clicks to the elements behind it. Still a fantastic answer though! Very happy to be able to do this without javascript. – Luc Apr 24 '19 at 15:12
  • Use a "data-tooltip" attribute instead of a "tooltip". Then your HTML validates. – Pascal_dher Nov 19 '19 at 10:07
  • @Pascal_dher yes, I know. I've never cared much about that, but what's right is right, and since you've said it out loud... done :) – Andrea Ligios Nov 19 '19 at 10:54
  • 3
    @LinusGeffarth you can do it with white-space: pre-wrap; on current Chrome. I haven't tested other browsers though. – Taugenichts Mar 09 '20 at 22:47
  • Thanks @Taugenichts! Seems legit: https://caniuse.com/#feat=mdn-css_properties_white-space_pre-wrap – Andrea Ligios Mar 10 '20 at 00:40
  • Good answer. Implementing functionality in CSS - when posibble - is usually a much better idea than doing it in JavaScript. – Henke Jul 09 '20 at 08:34
  • 3
    I forked @AndreaLigios solution above to use css animations instead of transitions, because opacity was causing problems with my setup in edge cases when the tooltip was near the edge of the screen in mobile devices. Here it is: https://jsfiddle.net/dimitrisscript/d634bqtn/2/ – Dimitris Siakavelis Aug 26 '20 at 09:09
  • 4
    What @Luc said: if the tooltip content is very long it might lay over other clickable elements. The opacity is a purely visual effect. The element is still there and may overlap others. Better solution would be to use display: none as default and block on hover. – Frank Drebin Dec 17 '21 at 14:06
  • Great idea, flexible and customisable, compared to the simpler `title` alternative. Replacing `opacity:` 0->1 with `display:` none->block and setting `white-space: pre` is a must though, as others pointed out, in order to prevent the attribute taking space and triggering mouse events even when invisible, as well as allowing newlines in its contents. Just like the `title` alternative, if you change its contents at a faster rate than the transition one, it will always be hidden, so a bit of care is required in those cases. Its only drawback is that, unlike `title`, it can't be shown off window. – Yin Cognyto May 26 '22 at 14:33
  • Your tooltip missed up my page height and spawned random scrollbars because of your `opacity`; you say do not touch but I had to touch it and change that to `display`. – Beyondo Dec 22 '22 at 21:43
  • Your comment doesn't make any sense. This is not an out of the box third party plugin on GitHub, is a free proof of concept on Stackoverflow. The "do not change" is referred to the context of this specific example. You can - and should- modify this code to better fit your needs, including obviously your page's specific structure, styles, and look and feel. You can't copy it from here, drop it in your production site, then complaining it's not adapting to your page automatically. Stop me if there's something that doesn't add up. – Andrea Ligios Dec 23 '22 at 11:07
  • Don't forget to add `pointer-events: none;` in `[data-tooltip]:before`, otherwise the tooltip will show itself when hovering adjacent elements. – Codingwiz Jan 09 '23 at 19:49
  • @Codingwiz in the demo snippet above, it is not. It's probably related to other parts of your code – Andrea Ligios Jan 10 '23 at 10:58
141

You don't need JavaScript for this at all; just set the title attribute:

<div title="Hello, World!">
  <label>Name</label>
  <input type="text"/>
</div>

Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.

Demo in Stack Snippets

<div title="Hello, World!">
  <label>Name</label>
  <input type="text"/>
</div>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
cdhowie
  • 158,093
  • 24
  • 286
  • 300
19

Here's a pure CSS 3 implementation (with optional JS)

The only thing you have to do is set an attribute on any div called "data-tooltip" and that text will be displayed next to it when you hover over it.

I've included some optional JavaScript that will cause the tooltip to be displayed near the cursor. If you don't need this feature, you can safely ignore the JavaScript portion of this fiddle.

If you don't want the fade-in on the hover state, just remove the transition properties.

It's styled like the title property tooltip. Here's the JSFiddle: http://jsfiddle.net/toe0hcyn/1/

HTML Example:

<div data-tooltip="your tooltip message"></div>

CSS:

*[data-tooltip] {
    position: relative;
}

*[data-tooltip]::after {
    content: attr(data-tooltip);

    position: absolute;
    top: -20px;
    right: -20px;
    width: 150px;

    pointer-events: none;
    opacity: 0;
    -webkit-transition: opacity .15s ease-in-out;
    -moz-transition: opacity .15s ease-in-out;
    -ms-transition: opacity .15s ease-in-out;
    -o-transition: opacity .15s ease-in-out;
    transition: opacity .15s ease-in-out;

    display: block;
    font-size: 12px;
    line-height: 16px;
    background: #fefdcd;
    padding: 2px 2px;
    border: 1px solid #c0c0c0;
    box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.4);
}

*[data-tooltip]:hover::after {
    opacity: 1;
}

Optional JavaScript for mouse position-based tooltip location change:

var style = document.createElement('style');
document.head.appendChild(style);

var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++) {
    var attr = allElements[i].getAttribute('data-tooltip');
    if (attr) {
        allElements[i].addEventListener('mouseover', hoverEvent);
    }
}

function hoverEvent(event) {
    event.preventDefault();
    x = event.x - this.offsetLeft;
    y = event.y - this.offsetTop;

    // Make it hang below the cursor a bit.
    y += 10;

    style.innerHTML = '*[data-tooltip]::after { left: ' + x + 'px; top: ' + y + 'px  }'

}
Steven Linn
  • 696
  • 5
  • 14
17

Here's a nice jQuery Tooltip:

https://jqueryui.com/tooltip/

To implement this, just follow these steps:

  1. Add this code in your <head></head> tags:

    <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>    
    <script type="text/javascript">
    $("[title]").tooltip();
    </script> 
    <style type="text/css"> 
    
    /* tooltip styling. by default the element to be styled is .tooltip  */
    .tooltip {
        display:none;
        background:transparent url(https://dl.dropboxusercontent.com/u/25819920/tooltip/black_arrow.png);
        font-size:12px;
        height:70px;
        width:160px;
        padding:25px;
        color:#fff;
    }
    </style> 
    
  2. On the HTML elements that you want to have the tooltip, just add a title attribute to it. Whatever text is in the title attribute will be in the tooltip.

Note: When JavaScript is disabled, it will fallback to the default browser/operating system tooltip.

Nathan
  • 11,814
  • 11
  • 50
  • 93
  • I used your solution here. https://stackoverflow.com/questions/71043039/tooltip-is-not-closing-with-select2. But I am not getting a good result. Thanks. – abu abu Mar 02 '22 at 23:17
16

I did something that should be able to be adapted to a div as well.

HTML

<td>
    <%# (Eval("Name").ToString().Length > 65) ? Eval("Name").ToString().Substring(0, 60) + "..." : Eval("Name")%>
    <span class="showonhover">
        <a href="#"><%# (Eval("Name").ToString().Length > 65) ? "More" : "" %></a>
        <span class="hovertext">
            <%# Eval("Name") %>
        </span>
    </span>
</td>

CSS

.showonhover .hovertext { display: none;}
.showonhover:hover .hovertext {display: inline;}
a.viewdescription {color:#999;}
a.viewdescription:hover {background-color:#999; color: White;}
.hovertext {position:absolute;z-index:1000;border:1px solid #ffd971;background-color:#fffdce;padding:11px;width:150px;font-size: 0.75em;}

For a more in-depth discussion, see my post:

A simple Formatted ToolTip text on hover

Narnian
  • 3,858
  • 1
  • 26
  • 29
  • 11
    Question was for a html solution not some .net server-side magic. – Michał Šrajer Dec 22 '11 at 23:22
  • 6
    The .net code is in there to show truncation. The approach using html and css is still valid. – Mark Swardstrom Apr 22 '13 at 20:03
  • 1
    This is the easiest and best solution, as it doesn't rely on JS. Just make the span.showonhover focusable or move the span.hovertext into the link and you are fully accessible for screen readers (and therefore better than the title-attribute solution). Oh, and forget about <%# ... %> – chaenu Sep 08 '14 at 15:26
15

Okay, here's all of your bounty requirements met:

  • No jQuery
  • Instant appearing
  • No dissapearing until the mouse leaves the area
  • Fade in/out effect incorporated
  • And lastly.. simple solution

Here's a demo and link to my code (JSFiddle)

Here are the features that I've incorporated into this purely JS, CSS and HTML5 fiddle:

  • You can set the speed of the fade.
  • You can set the text of the tooltip with a simple variable.

HTML:

<div id="wrapper">
    <div id="a">Hover over this div to see a cool tool tip!</div>
</div>

CSS:

#a{
    background-color:yellow;
    padding:10px;
    border:2px solid red;    
}

.tooltip{
    background:black;
    color:white;
    padding:5px;
    box-shadow:0 0 10px 0 rgba(0, 0, 0, 1);
    border-radius:10px;
    opacity:0;
}

JavaScript:

var div = document.getElementById('wrapper');
var a = document.getElementById("a");
var fadeSpeed = 25; // a value between 1 and 1000 where 1000 will take 10
                    // seconds to fade in and out and 1 will take 0.01 sec.
var tipMessage = "The content of the tooltip...";

var showTip = function(){    
    var tip = document.createElement("span");
    tip.className = "tooltip";
    tip.id = "tip";
    tip.innerHTML = tipMessage;
    div.appendChild(tip);
    tip.style.opacity="0"; // to start with...
    var intId = setInterval(function(){
        newOpacity = parseFloat(tip.style.opacity)+0.1;
        tip.style.opacity = newOpacity.toString();
        if(tip.style.opacity == "1"){
            clearInterval(intId);
        }
    }, fadeSpeed);
};
var hideTip = function(){
    var tip = document.getElementById("tip");
    var intId = setInterval(function(){
        newOpacity = parseFloat(tip.style.opacity)-0.1;
        tip.style.opacity = newOpacity.toString();
        if(tip.style.opacity == "0"){
            clearInterval(intId);
            tip.remove();
        }
    }, fadeSpeed);
    tip.remove();
};

a.addEventListener("mouseover", showTip, false);
a.addEventListener("mouseout", hideTip, false);
Anshu Dwibhashi
  • 4,617
  • 3
  • 28
  • 59
6

You can create custom CSS tooltips using a data attribute, pseudo elements and content: attr() eg.

http://jsfiddle.net/clintioo/gLeydk0k/11/

<div data-tooltip="This is my tooltip">
    <label>Name</label>
    <input type="text" />
</div>

.

div:hover:before {
    content: attr(data-tooltip);
    position: absolute;
    padding: 5px 10px;
    margin: -3px 0 0 180px;
    background: orange;
    color: white;
    border-radius: 3px;
}

div:hover:after {
    content: '';
    position: absolute;
    margin: 6px 0 0 3px;
    width: 0;
    height: 0;
    border-top: 5px solid transparent;
    border-right: 10px solid orange;
    border-bottom: 5px solid transparent;
}

input[type="text"] {
    width: 125px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
6

You can use title. it'll work for just about everything

<div title="Great for making new friends through cooperation.">

<input script=JavaScript type=button title="Click for a compliment" onclick="window.alert('Your hair reminds me of a sunset across a prairie')" value="making you happy">

<table title="Great job working for those who understand the way i feel">

just think of any tag that can be visible to html window and insert a title="whatever tooltip you'd like" inside it's tag and you got yourself a tooltip.

Ronnie Matthews
  • 473
  • 4
  • 13
6

I have developed three type fade effects :

/* setup tooltips */
    .tooltip {
      position: relative;
    }
    .tooltip:before,
    .tooltip:after {
      display: block;
      opacity: 0;
      pointer-events: none;
      position: absolute;
    }
    .tooltip:after {
     border-right: 6px solid transparent;
     border-bottom: 6px solid rgba(0,0,0,.75); 
      border-left: 6px solid transparent;
      content: '';
      height: 0;
        top: 20px;
        left: 20px;
      width: 0;
    }
    .tooltip:before {
      background: rgba(0,0,0,.75);
      border-radius: 2px;
      color: #fff;
      content: attr(data-title);
      font-size: 14px;
      padding: 6px 10px;
        top: 26px;
      white-space: nowrap;
    }

    /* the animations */
    /* fade */
    .tooltip.fade:after,
    .tooltip.fade:before {
      transform: translate3d(0,-10px,0);
      transition: all .15s ease-in-out;
    }
    .tooltip.fade:hover:after,
    .tooltip.fade:hover:before {
      opacity: 1;
      transform: translate3d(0,0,0);
    }

    /* expand */
    .tooltip.expand:before {
      transform: scale3d(.2,.2,1);
      transition: all .2s ease-in-out;
    }
    .tooltip.expand:after {
      transform: translate3d(0,6px,0);
      transition: all .1s ease-in-out;
    }
    .tooltip.expand:hover:before,
    .tooltip.expand:hover:after {
      opacity: 1;
      transform: scale3d(1,1,1);
    }
    .tooltip.expand:hover:after {
      transition: all .2s .1s ease-in-out;
    }

    /* swing */
    .tooltip.swing:before,
    .tooltip.swing:after {
      transform: translate3d(0,30px,0) rotate3d(0,0,1,60deg);
      transform-origin: 0 0;
      transition: transform .15s ease-in-out, opacity .2s;
    }
    .tooltip.swing:after {
      transform: translate3d(0,60px,0);
      transition: transform .15s ease-in-out, opacity .2s;
    }
    .tooltip.swing:hover:before,
    .tooltip.swing:hover:after {
      opacity: 1;
      transform: translate3d(0,0,0) rotate3d(1,1,1,0deg);
    }

    /* basic styling: has nothing to do with tooltips: */
    h1 {
      padding-left: 50px;
    }
    ul {
      margin-bottom: 40px;
    }
    li {
      cursor: pointer; 
      display: inline-block; 
      padding: 0 10px;
    }
 <h1>FADE</h1>

      <div class="tooltip fade" data-title="Hypertext Markup Language">
      <label>Name</label>
      <input type="text"/>
      </div>
      

    <h1>EXPAND</h1>

      <div class="tooltip expand" data-title="Hypertext Markup Language">
      <label>Name</label>
      <input type="text"/>
      </div>
      

    <h1>SWING</h1>

      <div class="tooltip swing" data-title="Hypertext Markup Language"> 
      <label>Name</label>
      <input type="text"/>
      </div>
     
Nims Patel
  • 1,048
  • 9
  • 19
5

You can toggle a child div during onmouseover and onmouseout like this:

function Tooltip(el, text) {
  el.onmouseover = function() {
    el.innerHTML += '<div class="tooltip">' + text + '</div>' 
    }
  el.onmouseout = function() {
    el.removeChild(el.querySelector(".tooltip"))
  }
}

//Sample Usage
Tooltip(document.getElementById("mydiv"),"hello im a tip div")

Example in Stack Snippets & jsFiddle

function Tooltip(el, text) {
  el.onmouseover = function() {
    el.innerHTML += '<div class="tooltip">' + text + '</div>'
  }
  el.onmouseout = function() {
    el.removeChild(el.querySelector(".tooltip"))
  }
}

//Sample Usage
Tooltip(document.getElementById("mydiv"), "I'm a tooltip")
#mydiv {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 50px;
  padding: 5px 10px;
  background-color: #e2f7ff;
  box-shadow: 1px 1px 1px 0px #cecece;
}

.tooltip {
  position: absolute;
  display: inline-block;
  white-space: nowrap;
  width: auto;
  height: auto;
  background-color: #11121b;
  color: white;
  padding: 4px 6px;
  border-radius: 3px;
  z-index: 99;
  left: 100%;
  top: 0;
}
<div id="mydiv"> This is just a div </div>
KyleMit
  • 30,350
  • 66
  • 462
  • 664
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
5

you can also use this as tooltip...It works same but you have to write extra tag thats it..

<abbr title="THis is tooltip"></abbr>
4

The simplest way would be to set position: relative on the containing element and position: absolute on the tooltip element inside the container to make it float relative to the parent (containing element). For example:

<div style="background: yellow;">
    <div style="display: inline-block; position: relative; background: pink;">
        <label>Name</label>
        <input type="text" />

        <div style="background: #e5e5e5; position: absolute; top: -10px; left: 0; right: 0;">
            Tooltip text
        </div>
    </div>
</div>
designcise
  • 4,204
  • 1
  • 17
  • 13
4

Try this. You can do it with only css and I have only added data-title attribute for tooltip.

.tooltip{
  position:relative;
  display: inline-block;
}
.tooltip[data-title]:hover:after {
  content: attr(data-title);
  padding: 4px 8px;
  color: #fff;
  position: absolute;
  left: 0;
  top: 110%;
  white-space: nowrap;  
  border-radius: 5px;  
  background:#000;
}
<div data-title="My tooltip" class="tooltip">
    <label>Name</label>
    <input type="text"/>
</div>
    
ankita patel
  • 4,201
  • 1
  • 13
  • 28
4

Here's a simple tooltip implementation that keeps into account the position of your mouse as well as the height and width of your window :

function showTooltip(e) {
  var tooltip = e.target.classList.contains("tooltip")
      ? e.target
      : e.target.querySelector(":scope .tooltip");
  tooltip.style.left =
      (e.pageX + tooltip.clientWidth + 10 < document.body.clientWidth)
          ? (e.pageX + 10 + "px")
          : (document.body.clientWidth + 5 - tooltip.clientWidth + "px");
  tooltip.style.top =
      (e.pageY + tooltip.clientHeight + 10 < document.body.clientHeight)
          ? (e.pageY + 10 + "px")
          : (document.body.clientHeight + 5 - tooltip.clientHeight + "px");
}

var tooltips = document.querySelectorAll('.couponcode');
for(var i = 0; i < tooltips.length; i++) {
  tooltips[i].addEventListener('mousemove', showTooltip);
}
.couponcode {
    color: red;
    cursor: pointer;
}

.couponcode:hover .tooltip {
    display: block;
}

.tooltip {
    position: absolute;
    white-space: nowrap;
    display: none;
    background: #ffffcc;
    border: 1px solid black;
    padding: 5px;
    z-index: 1000;
    color: black;
}
Lorem ipsum dolor sit amet, <span class="couponcode">consectetur
adipiscing<span class="tooltip">This is a tooltip</span></span>
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in <span
class="couponcode">reprehenderit<span class="tooltip">This is
another tooltip</span></span> in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est <span
class="couponcode">laborum<span class="tooltip">This is yet
another tooltip</span></span>.

(see also this Fiddle)

John Slegers
  • 45,213
  • 22
  • 199
  • 169
3
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI tooltip</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>  
  <script>
  $(function() {
    $("#tooltip").tooltip();
  });
  </script>
</head>
<body>
<div id="tooltip" title="I am tooltip">mouse over me</div>
</body>
</html>

You can also customise tooltip style. Please refer this link: http://jqueryui.com/tooltip/#custom-style

sanman
  • 770
  • 1
  • 7
  • 15
3

A CSS3-only solution could be:

CSS3:

div[id^="tooltip"]:after {content: attr(data-title); background: #e5e5e5; position: absolute; top: -10px; left:  0; right: 0; z-index: 1000;}

HTML5:

<div style="background: yellow;">
    <div id="tooltip-1" data-title="Tooltip Text" style="display: inline-block; position: relative; background: pink;">
        <label>Name</label>
        <input type="text" />
    </div>
</div>

You could then create a tooltip-2 div the same way... you can of course also use the title attribute instead of data attribute.

designcise
  • 4,204
  • 1
  • 17
  • 13
  • 1
    Why the hell would you use an id to style something you want more instances of, and then use the `[id^=tooltip]` selector when you could have just used a class and `.tooltip`? – Stephan Muller Sep 11 '14 at 19:21
  • You're right. I started off with ids, so followed it on and totally missed it. But hey, someone might benefit from it. Oh and by the way, we could even use an attribute selector for that matter to select "data-title" (e.g. ```div[data-title])``` without having to add extra markup. – designcise Sep 15 '14 at 18:44
3

you can do it with simple css... jsfiddle here you can see the example

below css code for tooltip

[data-tooltip] {
  position: relative;
  z-index: 2;
  cursor: pointer;
}

/* Hide the tooltip content by default */
[data-tooltip]:before,
[data-tooltip]:after {
  visibility: hidden;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0;
  pointer-events: none;
}

/* Position tooltip above the element */
[data-tooltip]:before {
  position: absolute;
  bottom: 150%;
  left: 50%;
  margin-bottom: 5px;
  margin-left: -80px;
  padding: 7px;
  width: 160px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  background-color: #000;
  background-color: hsla(0, 0%, 20%, 0.9);
  color: #fff;
  content: attr(data-tooltip);
  text-align: center;
  font-size: 14px;
  line-height: 1.2;
}

/* Triangle hack to make tooltip look like a speech bubble */
[data-tooltip]:after {
  position: absolute;
  bottom: 150%;
  left: 50%;
  margin-left: -5px;
  width: 0;
  border-top: 5px solid #000;
  border-top: 5px solid hsla(0, 0%, 20%, 0.9);
  border-right: 5px solid transparent;
  border-left: 5px solid transparent;
  content: " ";
  font-size: 0;
  line-height: 0;
}

/* Show tooltip content on hover */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
  visibility: visible;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
  filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
}
satyajit rout
  • 1,623
  • 10
  • 20
2

Without using any API You can do something like this too by using pure CSS and Jquery Demo

HTML

<div class="pointer_tooltip"> 
    Click & Drag to draw the area
</div>

CSS

.pointer_tooltip{
  width : auto;
  height : auto;
  padding : 10px;
  border-radius : 5px;
  background-color : #fff;
  position: absolute;
}

Jquery

$(document).mousemove(function( event ) {
    var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";   

    //set the actuall width
    $('.pointer_tooltip').width($('.pointer_tooltip').width());
    var position_top = event.pageY+18;
    var position_left = event.pageX-60;          
    var width=$('body').width()-$('.pointer_tooltip').width();

    //check if left not minus
    if(position_left<0){
      position_left=10;
    }else if(position_left > width){
     position_left=width-10;
    }       


    $('.pointer_tooltip').css('top',position_top+'px');
    $('.pointer_tooltip').css('left',position_left+'px');
});
Amin Kodaganur
  • 646
  • 6
  • 19
2

You can make tooltip using pure CSS.Try this one.Hope it should help you to solve your problem.

HTML

<div class="tooltip"> Name
    <span class="tooltiptext">Add your tooltip text here.</span>
</div>

CSS

.tooltip {
        position: relative;
        display: inline-block;
        cursor: pointer;
    }

    .tooltip .tooltiptext {
        visibility: hidden;
        width: 270px;
        background-color: #555;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 5px 0;
        position: absolute;
        z-index: 1;
        bottom: 125%;
        left: 50%;
        margin-left: -60px;
        opacity: 0;
        transition: opacity 1s;
    }

    .tooltip .tooltiptext::after {
        content: "";
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: #555 transparent transparent transparent;
    }

    .tooltip:hover .tooltiptext {
        visibility: visible;
        opacity: 1;
    }
Faisal
  • 4,591
  • 3
  • 40
  • 49
  • I used this here. https://stackoverflow.com/questions/71320946/tooltip-is-not-appearing-properly. But didn't get any good result. Thanks. – abu abu Mar 02 '22 at 23:10
2

Tooltips Position pure css

      div {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%); /* IE 9 */
        -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ 
       
        text-align: center;
      }       
 
      .tooltip {
        position: relative;
        display: inline-block;
        border-bottom: 1px dotted black;
      }

      .tooltip .tooltiptext {
        visibility: hidden;
        width: 120px;
        background-color: black;
        color: #fff;
        //text-align: center;
        border-radius: 6px;
        padding: 5px 0;

        /* Position the tooltip */
        position: absolute;
        z-index: 1;
      }

      .tooltip:hover .tooltiptext {
        visibility: visible;
      }  
     
      .toolLeft {
        top: -5px;
        right: 105%;
      }     
     
      .toolRight {
        top: -5px;
        left: 105%;
      }
     
      .toolTop {
        bottom: 100%;
        left: 50%;
        margin-left: -60px;
      }
     
      .toolBottom {
        top: 100%;
        left: 50%;
        margin-left: -60px;
      }
    <div>
   
      <div class="tooltip">Top <span class="tooltiptext toolTop">Tooltip text</span></div><br />
      <div class="tooltip">Left  <span class="tooltiptext toolLeft">Tooltip text</span></div><br />   
      <div class="tooltip">Right <span class="tooltiptext toolRight">Tooltip text</span></div><br />
      <div class="tooltip">Bottom  <span class="tooltiptext toolBottom">Tooltip text</span></div><br />   
   
    </div>
antelove
  • 3,216
  • 26
  • 20
1

There are lots of answers to this question but still may be it will help someone. It is for all left, right, top, bottom positions.

Here is the css:

    .m-tb-5 {
        margin-top: 2px;
        margin-bottom: 2px;
    }
    [data-tooltip] {
        display: inline-block;
        position: relative;
        cursor: help;
        padding: 3px;
    }
    /* Tooltip styling */
    [data-tooltip]:before {
        content: attr(data-tooltip);
        display: none;
        position: absolute;
        background: #000;
        color: #fff;
        padding: 3px 6px;
        font-size: 10px;
        line-height: 1.4;
        min-width: 100px;
        text-align: center;
        border-radius: 4px;
    }
    /* Dynamic horizontal centering */
    [data-tooltip-position="top"]:before,
    [data-tooltip-position="bottom"]:before {
        left: 50%;
        -ms-transform: translateX(-50%);
        -moz-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
    }
    /* Dynamic vertical centering */
    [data-tooltip-position="right"]:before,
    [data-tooltip-position="left"]:before {
        top: 50%;
        -ms-transform: translateY(-50%);
        -moz-transform: translateY(-50%);
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    [data-tooltip-position="top"]:before {
        bottom: 100%;
        margin-bottom: 6px;
    }
    [data-tooltip-position="right"]:before {
        left: 100%;
        margin-left: 6px;
    }
    [data-tooltip-position="bottom"]:before {
        top: 100%;
        margin-top: 6px;
    }
    [data-tooltip-position="left"]:before {
        right: 100%;
        margin-right: 6px;
    }

    /* Tooltip arrow styling/placement */
    [data-tooltip]:after {
        content: '';
        display: none;
        position: absolute;
        width: 0;
        height: 0;
        border-color: transparent;
        border-style: solid;
    }
    /* Dynamic horizontal centering for the tooltip */
    [data-tooltip-position="top"]:after,
    [data-tooltip-position="bottom"]:after {
        left: 50%;
        margin-left: -6px;
    }
    /* Dynamic vertical centering for the tooltip */
    [data-tooltip-position="right"]:after,
    [data-tooltip-position="left"]:after {
        top: 50%;
        margin-top: -6px;
    }
    [data-tooltip-position="top"]:after {
        bottom: 100%;
        border-width: 6px 6px 0;
        border-top-color: #000;
    }
    [data-tooltip-position="right"]:after {
        left: 100%;
        border-width: 6px 6px 6px 0;
        border-right-color: #000;
    }

    [data-tooltip-position="left"]:after {
        right: 100%;
        border-width: 6px 0 6px 6px;
        border-left-color: #000;
    }
    /* Show the tooltip when hovering */
    [data-tooltip]:hover:before,
    [data-tooltip]:hover:after {
        display: block;
        z-index: 50;
    }

And the HTML tag can be like this:

<p data-tooltip-position="right" data-tooltip="Some tooltip text here" title="">Text Here</p>

<p data-tooltip-position="left" data-tooltip="Some tooltip text here" title="">Text Here</p>

<p data-tooltip-position="top" data-tooltip="Some tooltip text here" title="">Text Here</p>

<p data-tooltip-position="bottom" data-tooltip="Some tooltip text here" title="">Text Here</p>

Mukesh Joshi
  • 2,784
  • 4
  • 24
  • 34
1

And my version

.tooltip{
display: inline;
position: relative; /** very important set to relative*/
}

.tooltip:hover:after{
background: #333;
background: rgba(0,0,0,.8);
border-radius: 5px;
bottom: 26px;
color: #fff;
content: attr(title); /**extract the content from the title */
left: 20%;
padding: 5px 15px;
position: absolute;
z-index: 98;
width: 220px;
}

.tooltip:hover:before{
border: solid;
border-color: #333 transparent;
border-width: 6px 6px 0 6px;
bottom: 20px;
content: "";
left: 50%;
position: absolute;
z-index: 99;
}

Then the HTML

<div title="This is some information for our tooltip." class="tooltip">bar </div>
Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
1

You can try bootstrap tooltips.

$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

further reading here

1inMillion
  • 65
  • 7
0

I created a kind of formula for it. First this is the html

<div class="tooltip-container">
  <button class="tooltip-tarjet">
    My Button
  </button>
  <div class="tooltip-element"> 
    This is my tooltip content right here...
  </div>
</div>

Now the css for it

.tooltip-container { 
  /* it contains the tooltip message and the one firing the tooltip
   * it has position relative since it allows for a better responsive positioning
   * of the tooltip-element */
  display: inline-block;
  position: relative;
  flex-direction: row;
}
.tooltip-tarjet:hover + .tooltip-element {
  /* this selector rule matches the tooltip-element right after
   * tooltip-tarjet at a hover action
   *  */
  display: inline-block;
  position: absolute;
  background-color: #869096;
  color: white;
  opacity: 1;
  transition: all 1s;
}
.tooltip-element { 
  /* here goes the tooltip-element styles and positioning, now your
   * tooltip element will always remain to your desired positionno matter
   * the screen size at hand 
   *  */ 
  display: none; 
  opacity: 0;
  text-align: center;
  padding: 7px;
  z-index: 10;
  width: 200px;
  left: -60px;
  bottom: 48px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  font-size: 12px;
  line-height: 1.5;
}
Pepe Alvarez
  • 1,218
  • 1
  • 9
  • 15