1

[Vue.js] Tooltip

 2 years ago
source link: http://siongui.github.io/2017/03/05/vuejs-tooltip/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Vue.js] Tooltip

March 05, 2017

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/[email protected]/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:

[2]vuejs tooltip - Google search


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK