SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Custom Tooltip Widget

Tooltip

Build lightweight CSS + jQuery tooltips that appear on hover/focus and disappear on leave/blur.

Example
const $tip = $("<div>").attr({id:"tooltip",role:"tooltip"}).appendTo("body").hide();
$(document).on("mouseenter focusin", "[data-tooltip]", function(e) {
  const $el = $(this);
  $tip.text($el.data("tooltip")).show();
  const r = this.getBoundingClientRect();
  $tip.css({ top: r.top - $tip.outerHeight() - 8 + window.scrollY, left: r.left + r.width/2 - $tip.outerWidth()/2 });
  $el.attr("aria-describedby","tooltip");
}).on("mouseleave focusout", "[data-tooltip]", function() {
  $tip.hide(); $(this).removeAttr("aria-describedby");
});
Pro Tip

Link the tooltip to its trigger with aria-describedby="tooltip" so screen readers announce the text.