packages/lit-dev-content/site/tutorials/content/tooltip/03.md
To setup interactivity, add event listeners which call the show and
hide methods. First, define arrays of the relevant events above the class
definition:
// Events to turn on/off the tooltip
const enterEvents = ['pointerenter', 'focus'];
const leaveEvents = ['pointerleave', 'blur', 'keydown', 'click'];
Now add a target property which indicates the element being hinted
by the tooltip. Create a property accessor inside the class that manages
adding and removing event handlers:
{% switchable-sample %}
_target: Element|null = null;
get target() {
return this._target;
}
set target(target: Element|null) {
// Remove events from existing target
if (this.target) {
enterEvents.forEach(name =>
this.target!.removeEventListener(name, this.show));
leaveEvents.forEach(name =>
this.target!.removeEventListener(name, this.hide));
}
// Add events to new target
if (target) {
enterEvents.forEach(name =>
target!.addEventListener(name, this.show));
leaveEvents.forEach(name =>
target!.addEventListener(name, this.hide));
}
this._target = target;
}
_target = null;
get target() {
return this._target;
}
set target(target) {
// Remove events from existing target
if (this.target) {
enterEvents.forEach((name) =>
this.target.removeEventListener(name, this.show)
);
leaveEvents.forEach((name) =>
this.target.removeEventListener(name, this.hide)
);
}
// Add events to new target
if (target) {
enterEvents.forEach((name) => target.addEventListener(name, this.show));
leaveEvents.forEach((name) => target.addEventListener(name, this.hide));
}
this._target = target;
}
{% endswitchable-sample %}
The user can set the tooltip's target imperatively, but to make the element easy
to use declaratively in HTML, if a target hasn't been set, default it to the
previous DOM element when the tooltip is connected. There are fancier ways to
manage the target declaratively, but this should suffice for now. To the end of
connectedCallback add:
connectedCallback() {
//...
this.target ??= this.previousElementSibling;
}
{% aside "info" "no-header" %}
The nullish assignment operator is used to set the target only if it is unset.
{% endaside %}
The tooltip is now displayed based on user interactivity, but it's not positioned correctly, as you can see by moving your pointer over the right-most box.