Skip to content

Commit 94e893b

Browse files
committed
Skip replaced elements when initialising tooltips
Tooltips use `::before` and `::after`, which cannot work on replaced elements, the most common of which is `<img>`. We skip those elements when initialising the tooltips so that their `title` attribute is not removed and it can still be displayed by the browser when hovering over them.
1 parent 7b96a60 commit 94e893b

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

docs/content/components/tooltip.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,15 @@ Use the standard `title` attribute on any element to render a tooltip with smoot
1313
<a href="#" title="View your profile">Profile</a>
1414
```
1515
{% end %}
16+
17+
### Special Elements
18+
19+
The technique used to display these tooltips won't work on a few HTML elements, most notably `<img>`, so the native browser tooltip will be shown. To work around this issue, simply wrap those elements into another (e.g. `<div>` or `<span>`), and move the `title` attribute onto that parent element:
20+
21+
```html
22+
<span title="A title for the image">
23+
<img src="...">
24+
</span>
25+
```
26+
27+
Other elements affected by this are `<input type="image">`, `<video>`, `<embed>`, `<iframe>`, `<fencedframe>`, `<audio>`, `<canvas>`, and `<object>`.

src/js/tooltip.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,19 @@
66

77
document.addEventListener('DOMContentLoaded', () => {
88
const _attrib = 'title', _sel = '[title]';
9+
// https://developer.mozilla.org/en-US/docs/Glossary/Replaced_elements
10+
const _replacedElements = [
11+
'img', 'video', 'embed', 'iframe', 'fencedframe',
12+
// The following three elements are only sometimes considered replaced, but
13+
// we'll skip them nonetheless to at least get the native browser tooltip
14+
// if they can have it.
15+
'audio', 'canvas', 'object',
16+
];
17+
const isReplacedElement = el => _replacedElements.includes(el.localName);
18+
const isInputImage = el => el.localName == 'input' && el.type == 'image';
19+
920
const apply = el => {
21+
if (isReplacedElement(el) || isInputImage(el)) return;
1022
const t = el.getAttribute(_attrib);
1123
if (!t) return;
1224
el.setAttribute('data-tooltip', t);

0 commit comments

Comments
 (0)