[Vue.js] Tooltip


See demo first. Move the cursor (mouse pointer) to hover over the blue text with underline:

This is a tooltip example via Vue.js.

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

HTML:

<div id="vueapp">
  <div class="tooltip invisible" ref="tooltip"></div>
  This is a <span data-descr="hello, I am tooltip!">tooltip</span> example
  via <span data-descr="I am Vue.js!">Vue.js</span>.
</div>

<script src="https://unpkg.com/vue@2.2.1/dist/vue.js"></script>

The div element with ref="tooltip" [3] is the tooltip which shows the hint. If the mouse hovers over the span element with data-descr attribute, the tooltip will appear and the content of the tooltip is the texts in data-descr attribute.

CSS:

span[data-descr] {
    text-decoration: underline;
    color: blue;
    cursor: help;
}
.invisible {
    display: none;
}
.tooltip {
    position: absolute;
    background-color: yellow;
    border: 1px gray solid;
    border-radius: 3px;
    padding: 3px;
}

JavaScript:

'use strict';

new Vue({
  el: '#vueapp',
  mounted: function() {

    var tt = this.$refs.tooltip;

    function ShowTooltip(e) {
      var elm = e.target;
      tt.style.left = elm.offsetLeft + 'px';
      tt.style.top = (elm.offsetTop + elm.offsetHeight + 5) + 'px';
      tt.textContent = elm.dataset.descr;
      tt.classList.remove("invisible");
    }

    function HideTooltip(e) {
      tt.classList.add("invisible");
    }

    var spans = this.$el.querySelectorAll("span[data-descr]");
    for (var i = 0; i < spans.length; ++i) {
      var span = spans[i];
      span.addEventListener("mouseenter", ShowTooltip);
      span.addEventListener("mouseleave", HideTooltip);
    }

  }
})

In mounted hook of Vue instance [4], use querySelectorAll to find all span elements with data-descr attibute in vm.$el, and setup corresponding mouseenter/mouseleave event handlder to show/hide the tooltip.


Tested on:

  • Chromium Version 56.0.2924.76 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
  • Vue.js 2.2.1

References:

[1]Pure CSS Tooltip and JavaScript Implementation
[2]vuejs tooltip - Google search
[3]
[4]Instance Lifecycle Hooks - The Vue Instance — Vue.js