Tooltips for mobile browsers
Asked Answered
B

12

96

I currently set the title attribute of some HTML if I want to provide more information:

<p>An <span class="more_info" title="also called an underscore">underline</span> character is used here</p>

Then in CSS:

.more_info {
  border-bottom: 1px dotted;
}

Works very nice, visual indicator to move the mouse over and then a little popup with more information. But on mobile browsers, I don't get that tooltip. title attributes don't seem to have an effect. What's the proper way to give more information on a piece of text in a mobile browser? Same as above but use Javascript to listen for a click and then display a tooltip-looking dialog? Is there any native mechanism?

Buchheim answered 21/9, 2012 at 19:52 Comment(8)
Were you expecting to be able to hover with your finger?Listed
@sethflowers - good question :). Sure, I expected to be able to put my finger over the title attributed element and see a tooltip. Since phones can't yet detect hovering, I expected to need to press on the screen there too. I also kind of expected the mobile browser to deal with this intelligently since I did set the title attribute properly. Maybe some kind of indicator there was a tooltip and a way to see it... or maybe it automatically comes up until you click elsewhere... I guess I didn't expect the browser to disregard my HTML.Buchheim
unfortunately, that doesn't seem to be how mobile browsers work :(. would be nice thoughListed
For what it's worth, CSS hovers can register with a tap/click, as long as they aren't attached to a link or form... at least they do with the Opera Mobile emulator an Android emulator. Can't comment on iPhone or real devices. So a span:hover:after { content: attr(title) } would reveal more information.Pawn
@cimmanon, so you're saying the above code does work with a click in Opera and Android mobile emulated browsers? I had tried on an iPhone and it didn't. The span:hover:after css you mentioned, that is supposed to make this work on an iPhone as well?Buchheim
I don't own an iPhone, nor do I have an emulator for one, so I have no idea. On the emulators I mentioned, I do have elements that are hidden by default and revealed on :hover, and those absolutely do display when the element is clicked on.Pawn
span:hover:after { content: attr(title) } does not work on iPhone or emulator. If the text can be selected, the OS will attempt to select it...so anything longer than a click is going to work against what you're trying to do.Measly
To solve the selection problem you can add span[title] > * { user-select: none} span[title]:hover > * { user-select: auto }.Submerged
H
36

You can fake the title tooltip behavior with Javascript. When you click/tab on an element with a title attribute, a child element with the title text will be appended. Click again and it gets removed.

Javascript (done with jQuery):

$("span[title]").click(function () {
  var $title = $(this).find(".title");
  if (!$title.length) {
    $(this).append('<span class="title">' + $(this).attr("title") + '</span>');
  } else {
    $title.remove();
  }
});​

CSS:

.more_info {
  border-bottom: 1px dotted;
  position: relative;
}

.more_info .title {
  position: absolute;
  top: 20px;
  background: silver;
  padding: 4px;
  left: 0;
  white-space: nowrap;
}

Demo: http://jsfiddle.net/xaAN3/

Hafner answered 21/9, 2012 at 21:39 Comment(7)
This looks like it might provide a solution for me - however, can this be modified to not have to use a .title?Prothallus
This looks great, but when I use it the hint text comes up nowhere need the element with the title I have just clicked. How can I modify this to get it appearing near the element I have clicked.Sleep
This can work but messes up when it comes to multiple paragraphs... See Fiddle: jsfiddle.net/xaAN3/378Likewise
You should get rid of the more_info class and use an attribute selector instead! :) developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectorsFizgig
It's better to use mouseleave and mouseenter, if you want same behaviour as title.Carrero
There is some potential for improvement, because (a) long title text at a small HTML element could run out of view/sight. And (b) the tooltips can overlap (because there is no mechanism to ensure that only one tooltip is opened) and (c) the user has to explicitly close an opened tooltip. (d) you should use z-index to show that tooltip above the normal content. This example shows how a to d can get achieved with the hover element in CSS: w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltipTinned
Another issue with this solution is that by not using the actual html title property, the title value is not being provided to screen readers which is necessary for it to be accessible. The custom tooltip would require additional logic to ensure that he screen reader gets the information in another way (possibly by replicating the value to an aria-label property.Contend
L
44

Here is a CSS only solution. (Similar to @Jamie Pate 's answer, but without the JavaScript.)

We can use the pseudo class :hover, but I'm not sure all mobile browsers apply these styles when the element is tapped. I'm using pseudo class :focus because I'm guessing it's safer. However, when using pseudo class :focus we need to add tabindex="0" to elements that don't have a focus state intrinsically.

I'm using 2 @media queries to ensure all mobile devices are targeted. The (pointer: coarse) query will target any device that the primary input method is something "coarse", like a finger. And the (hover: none) query will target any device that the primary pointing system can't hover.

This snippet is all that's needed:

@media (pointer: coarse), (hover: none) {
      [title] {
        position: relative;
        display: inline-flex;
        justify-content: center;
      }
      [title]:focus::after {
        content: attr(title);
        position: absolute;
        top: 90%;
        color: #000;
        background-color: #fff;
        border: 1px solid;
        width: fit-content;
        padding: 3px;
      }
    }

/*Semantic Styling*/
body {
  display: grid;
  place-items: center;
  text-align: center;
  height: 100vh;
}

a {
  height: 40px;
  width: 200px;
  background: #fa4766;
  color: #fff;
  text-decoration: none;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 10px;
}

/*Functional Styling*/
@media (pointer: coarse), (hover: none) {
  [title] {
    position: relative;
    display: flex;
    justify-content: center;
  }
  [title]:focus::after {
    content: attr(title);
    position: absolute;
    top: 90%;
    color: #000;
    background-color: #fff;
    border: 1px solid;
    width: fit-content;
    padding: 3px;
  }

}
<a title="this is the Title text" tabindex="0">Tag with Title</a>

Obviously, you'll need to open this on a mobile device to test it. Here is a Pen with the same code.

Lidstone answered 12/3, 2020 at 18:49 Comment(11)
I do prefer css options over using javascript, however, your snippet is not generic enough. For example, how would it be applied to inline elements like the following: <p>This sentance has an <abbr title="abbreviation">abbr</abbr> in it.</p> I've been trying to apply it, but can't seem to grasp it yet. Also, there are <title> tags in svg that I would like to apply this to as well.Genic
@LadyAleena I switched display: flex to inline-flex it works fine for your example. Also note that the only reason I'm using flex, is to center the title element. However, display: inline-block works just fine and only slightly less pretty.Lidstone
How is the tabindex tied to the css you provided. It appears that without the tabindex, the css does not work.Genic
@LadyAleena tabindex makes the element focusable. Alternatively, pseudo class :hover can be used without tabindexLidstone
Wow! This should be the default behavior of the browser! 🎉🚀👍Neolatin
I'm wondering why you specify pointer:coarse. Wouldn't hover:none be enough - I assume we are only interested in checking whether the device allows hover or not.Canoewood
To clarify my previous comment, the combination of pointer:coarse and hover:none may rule out stylus-based screens (which have fine pointers but no hover ability).Canoewood
@Canoewood The comma between the two should be read as an or, so it wouldn't rule those out (but I also don't think the addition of pointer: coarse is actually necessary)Aberdare
I recommend adding white-space: pre to the pseudo element (::after) when you have multi-line titles. Also, font-size: small; line-height: 1 can help make the "tooltip" look much more like a real tooltip!Bistre
I've added a z-index: 1; to the (::after) so that the tooltip won't be covered by other elements (images in the next table row in my case).Whistle
On Android/Chrome 109, 1) My device(Galaxy S20) matches with hover: hover. So pointer: coarse is needed. 2) :focus, :hover work both. But without tabindex, the chrome displays quick search bottom popup for a selected word. So tabindex is needed.Edelman
H
36

You can fake the title tooltip behavior with Javascript. When you click/tab on an element with a title attribute, a child element with the title text will be appended. Click again and it gets removed.

Javascript (done with jQuery):

$("span[title]").click(function () {
  var $title = $(this).find(".title");
  if (!$title.length) {
    $(this).append('<span class="title">' + $(this).attr("title") + '</span>');
  } else {
    $title.remove();
  }
});​

CSS:

.more_info {
  border-bottom: 1px dotted;
  position: relative;
}

.more_info .title {
  position: absolute;
  top: 20px;
  background: silver;
  padding: 4px;
  left: 0;
  white-space: nowrap;
}

Demo: http://jsfiddle.net/xaAN3/

Hafner answered 21/9, 2012 at 21:39 Comment(7)
This looks like it might provide a solution for me - however, can this be modified to not have to use a .title?Prothallus
This looks great, but when I use it the hint text comes up nowhere need the element with the title I have just clicked. How can I modify this to get it appearing near the element I have clicked.Sleep
This can work but messes up when it comes to multiple paragraphs... See Fiddle: jsfiddle.net/xaAN3/378Likewise
You should get rid of the more_info class and use an attribute selector instead! :) developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectorsFizgig
It's better to use mouseleave and mouseenter, if you want same behaviour as title.Carrero
There is some potential for improvement, because (a) long title text at a small HTML element could run out of view/sight. And (b) the tooltips can overlap (because there is no mechanism to ensure that only one tooltip is opened) and (c) the user has to explicitly close an opened tooltip. (d) you should use z-index to show that tooltip above the normal content. This example shows how a to d can get achieved with the hover element in CSS: w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltipTinned
Another issue with this solution is that by not using the actual html title property, the title value is not being provided to screen readers which is necessary for it to be accessible. The custom tooltip would require additional logic to ensure that he screen reader gets the information in another way (possibly by replicating the value to an aria-label property.Contend
U
9

Given that a lot of people nowadays (2015) use mobile browsers, and title still hasn't found a form of exposure in mobile browsers, maybe it's time to deprecate reliance upon title for meaningful information.

It should never be used for critical information, but it is now becoming dubious for useful information, because if that information is useful and cannot be shown to half the users, then another way of showing it to almost all users needs to be found.

For static pages, perhaps some visible text near to the relevant control, even as fine print. For server-generated pages, browser sniffing could provide that only for mobile browsers. On the client side, javascript could be used to trap the focus event, via bubbling, to show the extra text next to the currently focussed element. That would minimise the screen space taken up, but would not necessarily be of much use, since, in a lot of instances, bringing focus to a control can only be done in a way that immediately activates its action, bypassing the ability to find out about it before using it!

Over all though, it appears that the difficulties of showing the title attribute on mobile devices, may lead to its demise, mostly due to needing an alternative that is more universal. That is a pity, because mobiles could use a way to show such extra info on-demand, without taking up the limited screen space.

It seems strange that the w3c and mobile browser makers did not do anything about this issue a long time ago. At least they could have displayed the title text on top of the menu that appears when a long press on a control is made.

Personally, I wish it was placed at the top of a right-click/long-touch menu, as it won't timeout, and would be available on all browsers.

The other alternative is to construct footnotes, so an [n] type superscript is put next to the element/text needing more info, linking to explanatory text in a list at the bottom of the page. Each of those can have a similar [n] type link back to the original text/element. That way, it keeps the display uncluttered, but provides easy bidirectional swapping in a simple way. Sometimes, old print media ways, with a little hyperlink help, are best.

The title attribute has been hijacked by some browsers to provide help text for the pattern attribute, in that its text pops up if the pattern doesn't match the text in the input element. Typically, it is to provide examples of the right format.

Uzzial answered 15/9, 2015 at 1:38 Comment(2)
For some pages, a list of footnotes would not be a bad idea. However, for some pages, it would created a very long list of them. For example, I am working on something with 121 <abbr> tags, each with their own title attribute. On top of that, every anchor I use has a title, and I have over 100 pages on my site each with anchor with title. So for this one page, I would have a footnote list of over 200 items. So, a list of footnotes on a mobile device would make the pages rather long depending on how many elements have titles.Genic
@LadyAleena. The alternative for such a plethora of abbr tags would be a glossary page, with the link to it opening the glossary in a new tab, because with so many, it is likely that the reader will be looking at some more expansions.Uzzial
S
9

As @cimmanon mentioned: span[title]:hover:after { content: attr(title) } gives you a rudimentary tooltip on touch screen devices. Unfortunately this has problems where the default ui behavior on touch screen devices is to select the text when any non-link/uicontrol is pressed.

To solve the selection problem you can add span[title] > * { user-select: none} span[title]:hover > * { user-select: auto }

A full solution may use some other techniques:

  • Add position: absolute background, border, box-shadow etc to make it look like a tooltip.
  • Add the class touched to body (via js) when the user uses any touch event. Then you can do body.touched [title]:hover ... without affecting desktop users

document.body.addEventListener('touchstart', function() {
  document.body.classList.add('touched');
});
[title] {
	border-bottom: 1px dashed rgba(0, 0, 0, 0.2);
	border-radius:2px;
	position: relative;
}
body.touched [title] > * {
	user-select: none;
}
body.touched [title]:hover > * {
	user-select: auto
}
body.touched [title]:hover:after {
	position: absolute;
	top: 100%;
	right: -10%;
	content: attr(title);
	border: 1px solid rgba(0, 0, 0, 0.2);
	background-color: white;
	box-shadow: 1px 1px 3px;
	padding: 0.3em;
	z-index: 1;
}
<div>Some text where a portion has a <span title="here's your tooltip">tooltip</span></div>
Submerged answered 6/11, 2016 at 21:38 Comment(0)
A
8

Slightly more elaborated version of flavaflo's answer:

  • Uses pre-defined div as pop-up that can hold HTML, rather than reading from a title attribute
  • Opens/closes on rollover if mouse is used
  • Opens on click (touch screen) and closes on click on the open pop-up or anywhere else on the document.

HTML:

  <span class="more_info">Main Text<div class="popup">Pop-up text can use <b>HTML</b><div></span>

CSS:

.more_info {
    border-bottom: 1px dotted #000;
  position: relative;
    cursor: pointer;
}

.more_info .popup {
    position: absolute;
    top: 15px; /*must overlap parent element otherwise pop-up doesn't stay open when rolloing over '*/
    background: #fff;
    border: 1px solid #ccc;
    padding: 8px;
    left: 0;
    max-width: 240px;
    min-width: 180px;
    z-index: 100;
    display: none;
}

JavaScript / jQuery:

$(document).ready(function () {

    //init pop-ups
    $(".popup").attr("data-close", false);

    //click on pop-up opener
    //pop-up is expected to be a child of opener
    $(".more_info").click(function () {
        var $title = $(this).find(".popup");
        //open if not marked for closing
        if ($title.attr("data-close") === "false") {
            $title.show();
        }
        //reset popup         
        $title.attr("data-close", false);
    });

    //mark pop-up for closing if clicked on
    //close is initiated by document.mouseup, 
    //marker will stop opener from re-opening it
    $(".popup").click(function () {
        $(this).attr("data-close",true);
    });

    //hide all pop-ups
    $(document).mouseup(function () {
        $(".popup").hide();

    });

    //show on rollover if mouse is used
    $(".more_info").mouseenter(function () {
        var $title = $(this).find(".popup");
        $title.show();
    });

    //hide on roll-out
    $(".more_info").mouseleave(function () {
        var $title = $(this).find(".popup");
        $title.hide();
    });  

});

Demo here https://jsfiddle.net/bgxC/yvs1awzk/

Asur answered 20/5, 2016 at 11:28 Comment(0)
B
6

Depending on how much information you want to give the user, a modal dialogue box might be an elegant solution.

Specifically, you could try the qTip jQuery plugin, which has a modal mode fired on $.click():

qTip Modal tooltip

Blanka answered 21/9, 2012 at 22:24 Comment(0)
C
5

I was searching for an easy CSS only solution, and this is really the most easy one I found:

<link rel="stylesheet" href="https://unpkg.com/balloon-css/balloon.min.css">

<span aria-label="Whats up!" data-balloon-pos="up">Hover me!</span>

Working example: https://jsfiddle.net/5pcjbnwg/

If you want to customize the tooltip, you find more info here: https://kazzkiq.github.io/balloon.css/

Canter answered 4/2, 2021 at 0:47 Comment(3)
There's an awful lot of complexity in that css file you've linked to...Adila
If you wonder, the core of what that library does is [aria-label]::after { content: attr(aria-label); opacity: 0; } [aria-label]:hover::after { opacity: 1; }. Everything else is just to make it look nicer.Aberdare
The minified CSS is a bit complex, but the Github project is well documented and the tooltip are nicely rendered, with a lot of rendering options (e.g. above/below, multilines). And it's pure CSS.Forewent
B
3

The title attribute is not supported in any mobile browsers **in a way that it would show the tooltip the same as to desktop mouse users** *(the attribute itself is ofcourse supported in the markup)*.
It's only basically for desktop users with a mouse, keyboard only users can't use it either, or screenreaders.

You can achieve almost similar with javascript as you said.

Barnabas answered 21/9, 2012 at 20:9 Comment(5)
Is there a good Javascript or jQuery library for this purpose?Buchheim
I have no clue, but it's not too hard to implement from scratch if not in any library.Barnabas
The title attribute is supported. The particular interaction requested is not. This is an important distinction.Gallicize
The basic problem is that tooltips are shown when hovering over an element, but mobile devices don't provide a way to "hover". When you touch the screen, it's either the beginning of a gesture (swiping to scroll, pinching to zoom, etc.) or it's a click if you don't move immediately. Maybe some day they'll have a way to detect the finger hanging an inch away from the screen.Haynes
@Buchheim My suggestion, which is a jQuery plugin, takes the tooltip (or modal) text the title attribute of an element.Blanka
P
2

To avoid using JavaScript, I used this CSS-only tooltip:

http://www.menucool.com/tooltip/css-tooltip

It works great in Mobile and Desktop, and you can customize the styles.

Pattipattie answered 12/10, 2022 at 23:20 Comment(0)
U
1

Thanks to @flavaflo for their answer. This works in most cases but if there is more than one title to lookup in the same paragraph, and one opens over the link to another, the unopened link shows through the first. This can be solved by dynamically changing the z-index of the title that has "popped up":

$("span[title]").click(function () {
  var $title = $(this).find(".title");
  if (!$title.length) {
    $(this).append('<span class="title">' + $(this).attr("title") + '</span>');
    $(this).css('z-index', 2);
  } else {
    $title.remove();
    $(this).css('z-index', 0);
  }
});​

Also, you can make both the hover over display and the click display multiline by adding &#10; (linefeed) to the title='' attribute, and then convert that to <br /> for the html click display:

$(this).append('<span class="title">' + $(this).attr("title").replace(/\\n/g, '<br />') + '</span>');
Untwine answered 18/3, 2018 at 11:58 Comment(0)
B
1

Extremely late to the party but for future visitors, here is a tweak of @Flavaflo's answer to fade the "tooltip" in and out

JQuery:

    $(".more_info").click(function () {
    var $title = $(this).find(".title");
    if (!$title.length) {
        $(this).append('<span class="title">' + $(this).attr("title") + '</span>');
    } else {
      $($title).fadeOut(250, function() {
          $title.remove();
      });
    }
});

CSS:

.more_info {
  border-bottom: 1px dotted;
  position: relative;
}

.more_info .title {
    position: absolute;
    top: 20px;
    background: green;
    padding: 4px;
    left: 0;
    color: white;
    white-space: nowrap;
    border-radius:3px;
    animation: fadeIn linear 0.15s;
}
@keyframes fadeIn {
  0% {opacity:0;}
  100% {opacity:1;}
}

Fiddle here: http://jsfiddle.net/L3paxb5g/

Balkh answered 2/7, 2021 at 9:28 Comment(0)
E
-1

I know this is an old question, but i have found a CSS solution that works on mobile too, it doesn't use title at all and it's easy to implement, explained here:

https://www.w3schools.com/css/css_tooltip.asp Explanation:

On mobile, with the touchscreen,the first input acts as css hover, so it works like a toggle tooltip when you press on it.

Code example:

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 2px dotted #666;
}

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

.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;
}

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div> 
Elvaelvah answered 25/5, 2020 at 22:35 Comment(2)
What makes you certain this works on the mobile web?Memoir
@HassanBaig I have tried it on my phone in different browsersElvaelvah

© 2022 - 2024 — McMap. All rights reserved.