Create V-Tooltip Directive in Vue.js

Creating a custom tooltip directive in Vue.js, often referred to as `v-tooltip`, allows you to add tooltip functionality to elements in your Vue application. Below is an example of how you can create a `v-tooltip` directive using Vue.js:

<button v-tooltip="'This is a tooltip'">Hover me</button>
<button v-tooltip="{ text: 'Another tooltip', position: 'bottom' }">Hover me</button>
<button v-tooltip="{ text: 'Tooltip with custom class', class: 'custom-tooltip' }">Hover me</button>

export default {
directives: {
tooltip: {
bind(el, binding) {

// Create tooltip element
const tooltipElement = document.createElement('div');
tooltipElement.className = 'tooltip';
tooltipElement.innerHTML = binding.value.text;

// Add custom class if provided
if (binding.value.class) {

// Position the tooltip
const position = binding.value.position || 'top';

// Show tooltip on hover
el.addEventListener('mouseenter', () => {

// Hide tooltip on mouse leave
el.addEventListener('mouseleave', () => {

.tooltip {
position: absolute;
background-color: black;
color: white;
padding: 5px;
border-radius: 3px;
z-index: 9999;
.tooltip-top {
bottom: 100%;
.tooltip-bottom {
top: 100%;
.tooltip-left {
right: 100%;
.tooltip-right {
left: 100%;
.custom-tooltip {
background-color: blue;
color: yellow;

In this example:

– We define a Vue component with buttons that will display tooltips when hovered over.
– We define a `tooltip` directive within the `directives` property of the Vue component.
– The `bind` function of the directive is called when the directive is attached to an element.
– Inside `bind`, we create a tooltip element and append it to the target element on hover.
– We position the tooltip based on the provided position (default is ‘top’).
– We provide flexibility by allowing customization of tooltip text, position, and class through directive modifiers.
– We define basic CSS for the tooltip, and allow customization through additional classes.

You can use this directive in your Vue.js application by simply adding `v-tooltip` to elements you want to have tooltips, passing the tooltip text and any other options as directive values.