[Dart] Tooltip


Simple tooltip implementation via dartlang.

Demo

The idea comes from the JavaScript implementation of my post [1]. The following is complete source code.

HTML:

<div class="tooltip invisible"></div>
This is a <span data-text="hello, I am tooltip!">tooltip</span> example via
<span data-text="programming language from Google">Dart</span>.

The texts in data-text attribute of the span element is the texts to be displayed in the tooltip when the cursor hovers over the span element.

CSS:

span[data-text] {
  text-decoration: underline;
  color: blue;
  cursor: help;
}

.invisible {
  display: none;
}

.tooltip {
  position: absolute;
  border: 1px gray solid;
  border-radius: 3px;
  padding: 3px;
}

Dart:

import 'dart:html';

DivElement tooltip = querySelector(".tooltip");

void ShowTooltip(Event e) {
  Element elm = e.target;
  tooltip.style.left = elm.offsetLeft.toString() + "px";
  tooltip.style.top = (elm.offsetTop + elm.offsetHeight + 5).toString() + "px";
  tooltip.text = elm.dataset["text"];
  tooltip.classes.remove("invisible");
}

void HideTooltip(Event e) {
  tooltip.classes.add("invisible");
}

void main() {
  var spans = querySelectorAll('span[data-text]');
  for (var span in spans) {
    span.onMouseEnter.listen(ShowTooltip);
    span.onMouseLeave.listen(HideTooltip);
  }
}

Use querySelectorAll to find all span elements with data-text attibute, and setup corresponding mouseenter/mouseleave event handlder to show/hide the tooltip.


Tested on: DartPad.


References:

[1]Pure CSS Tooltip and JavaScript Implementation
[2][Dart] Access HTML Data Attribute