Web Page Tool Tips

Sample Code
JavaScript
GitHub Gist

What It Is

Some simple JavaScript to create mouseover tooltips

Status

Last Reviewed:

I use it right now on this website – mouseover any internal link, like this one.

Details

Some simple JavaScript code to create mouseover tooltips. I was using a library called Tippy which is well-done, but just way, way too much. For the functionality I wanted, I got what I needed in about a dozen lines of code.

It doesn’t require any modification of the underlying HTML – it binds itself to whatever HTML you have.

There’s some pretty good documentation at the repo link, but note that this is not meant to be a “library” – it’s really just sample code. I didn’t generalize anything. You need to copy and modify.

Three steps:

  1. Form a collection of elements you want tips to appear for
  2. Create a function that – when passed the element that triggers the tip, returns the HTML to appear in the tip box
  3. Pass them both to bindTips
var elements = document.querySelectorAll('a');

function getTipContent(el) {
  var href = el.getAttribute('href');
  return href + " is a great URL!!!";
}

bindTips(elements, getTipContent);

Clearly, you can do this in one step if you want

bindTips(document.querySelectorAll("a"), (e) => { return e.dataset.tip; });

The function can do whatever you want. It is passed the element the tip was triggered on, and it should return the desired tip content in a string (it can be HTML).

For example, if you want to use the text of an attribute:

<a href="whatever" data-tooltip="This is a really cool website"/>
function getTipContent(el) {
  return el.dataset.tooltip;
}

When activated, the tip will display “Loading…” until getTipContent returns. Normally, this will be too fast to see, unless you’re doing some I/O (e.g. an HTTP request) to retrieve the tip content.

To style the tip, there is one CSS element (this is just for the appearance of the shape – the positioning is handled in the JavaScript).

div.tip {
  padding: 1em;
  border: solid 1px rgb(200,200,200);
  background: rgb(240,240,240);
}