Add a tooltip to a div

879,842

Solution 1

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.

Solution 2

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.

Solution 3

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>

Solution 4

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.

Solution 5

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  }'

}
Share:
879,842
user475685
Author by

user475685

Updated on February 07, 2022

Comments

  • user475685
    user475685 over 2 years

    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.

  • Michał Šrajer
    Michał Šrajer over 12 years
    Question was for a html solution not some .net server-side magic.
  • Mark Swardstrom
    Mark Swardstrom about 11 years
    The .net code is in there to show truncation. The approach using html and css is still valid.
  • RayLoveless
    RayLoveless about 10 years
    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;"
  • sscirrus
    sscirrus about 10 years
    @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.
  • RayLoveless
    RayLoveless about 10 years
    @sscirrus I agree. That's why you should NOT style your tooltips with "cursor: pointer;" (encourages clicking) which I see too often.
  • sscirrus
    sscirrus about 10 years
    @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!
  • leemes
    leemes almost 10 years
    If you only want to show a tooltip for some piece of text, like "details" for some keyword or something like that, use <abbr title="...">...</abbr> instead; browsers usually style this underlined with dashes / dots, indicating "there is more to tell, see my tooltip".
  • chaenu
    chaenu over 9 years
    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 <%# ... %>
  • Stephan Muller
    Stephan Muller over 9 years
    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?
  • Ke Vin
    Ke Vin over 9 years
    Quickly moving the cursor in and out spawns multiple tooltips that won't disappear in your jsfiddle.
  • designcise
    designcise over 9 years
    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.
  • Andre Mesquita
    Andre Mesquita almost 9 years
    I wonder, if tooltip apears at mouse position. Great customization.
  • Quentin Pradet
    Quentin Pradet over 8 years
    What is old IE here? IE 7? IE 8?
  • Michael
    Michael about 8 years
    The jquery tooltips link is broken on the "fancier javascript version" link, you can get it here: jqueryui.com/tooltip
  • John
    John about 8 years
    @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.
  • Andrea Ligios
    Andrea Ligios about 8 years
    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): jsfiddle.net/msn9frjw this way the glitch is still there, but less annoying
  • jhhoff02
    jhhoff02 over 7 years
    Great answer Andrea, the accepted answer is outdated. The jsfiddle helped lots.
  • Andrea Ligios
    Andrea Ligios over 7 years
    @marcusshep I keep being curious about your comment. Urban Dictionary gives many different meanings to your sentence, but none of them fits in here without a context. What the heck were you meaning with that ? :)
  • marcusshep
    marcusshep over 7 years
    @AndreaLigios hahaha No problem man. I simply wanted to say that this answer helped me a bunch with the problem I was working on at the time. I just said it in a funny way. :)
  • Johann
    Johann almost 7 years
    On Chrome, it can take a few seconds for the tooltip to appear. Kind of slow in my opinion.
  • Rohmer
    Rohmer over 6 years
    I love that there are two great answers to this question. One simple and the other customizable.
  • Yvonne Aburrow
    Yvonne Aburrow over 6 years
    true, but if the OP wants to style the tooltip in some way, then a CSS implementation is better
  • cdhowie
    cdhowie over 6 years
    @YvonneAburrow This answer is not only for the OP.
  • Yvonne Aburrow
    Yvonne Aburrow over 6 years
    fair enough. But sometimes one needs to write an essay in a tooltip, and in that situation the title attribute just doesn't cut it.
  • cdhowie
    cdhowie over 6 years
    @YvonneAburrow ... That's why there's multiple upvoted answers. If you need something simple and quick, title works. There are other answers that are more complex if you need something more complex. I'm honestly not sure what point you are trying to make here.
  • LinusGeffarth
    LinusGeffarth over 6 years
    This is awesome! But: how can we add a line break here? It seems to ignore <br> 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)
  • Reverend Bubbles
    Reverend Bubbles about 6 years
    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.
  • amitava mozumder
    amitava mozumder over 5 years
    Can it be done in some way that if the value of tooltip attribute is blank then no tooltip will be shown?
  • Andrea Ligios
    Andrea Ligios over 5 years
    @amitavamozumder simply include the tooltip="" part in the value you inject or not ;)
  • amitava mozumder
    amitava mozumder over 5 years
    @AndreaLigios sorry I didn't get that. which value you're talking about? and in which file?
  • Andrea Ligios
    Andrea Ligios over 5 years
    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
  • Luc
    Luc about 5 years
    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.
  • schlingel
    schlingel over 4 years
    I don't understand why you got so little number of votes. I was sure that there is a simple solution but people as well as w3schools come up with complex solutions for such a simple thing. thank you.
  • Pascal_dher
    Pascal_dher over 4 years
    Use a "data-tooltip" attribute instead of a "tooltip". Then your HTML validates.
  • Andrea Ligios
    Andrea Ligios over 4 years
    @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 :)
  • Taugenichts
    Taugenichts about 4 years
    @LinusGeffarth you can do it with white-space: pre-wrap; on current Chrome. I haven't tested other browsers though.
  • Andrea Ligios
    Andrea Ligios about 4 years
  • Henke
    Henke almost 4 years
    Good answer. Implementing functionality in CSS - when posibble - is usually a much better idea than doing it in JavaScript.
  • Dimitris Siakavelis
    Dimitris Siakavelis over 3 years
    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: jsfiddle.net/dimitrisscript/d634bqtn/2
  • Frank Drebin
    Frank Drebin over 2 years
    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.
  • Fumisky Wells
    Fumisky Wells over 2 years
    "newOpacity = ..." should be "var newOpacity = ...", right?
  • abu abu
    abu abu about 2 years
    I used this here. stackoverflow.com/questions/71320946/…. But didn't get any good result. Thanks.
  • abu abu
    abu abu about 2 years
    I used your solution here. stackoverflow.com/questions/71043039/…. But I am not getting a good result. Thanks.
  • DermotMW
    DermotMW about 2 years
    In terms of OP's fade in/out requirement, this doesn't work, but from my point of view, this is the easiest and best way to just put a tooltip on screen.
  • Yin Cognyto
    Yin Cognyto almost 2 years
    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
    Yin Cognyto almost 2 years
    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.