Categories
Vue 3 Projects

Create a Tooltip with Vue 3 and JavaScript

Spread the love

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a tooltip with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create tooltip

and select all the default options to create the project.

Create the Tooltip

To create the tooltip, we write:

<template>
  <div id="container">
    <button @mouseover="onHover">hover me</button>
    <div
      id="tooltip"
      :style="{ top: `${clientY}px`, left: `${clientX}px` }"
      v-if="show"
      @mouseout="show = false"
    >
      tooltip
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      show: false,
      clientX: 0,
      clientY: 0,
    };
  },
  methods: {
    onHover(e) {
      const { clientX, clientY } = e;
      this.show = true;
      this.clientX = clientX;
      this.clientY = clientY;
    },
  },
};
</script>

<style scoped>
#container {
  width: 95vw;
  height: 95vh;
  align-items: center;
  display: flex;
  justify-content: center;
}

#tooltip {
  border: 1px solid black;
  padding: 5px;
  position: absolute;
  background-color: white;
}
</style>

We have a button that triggers the tooltip when we hover over it.

The button has the @mouseover directive to run the onHover method.

onHover sets this.show to true to show the tooltip.

It also sets the clientX and clientY reactive properties to set the position of the tooltip.

Below that, we have a div with ID tooltip .

The style prop has an object that has the top and left properties to set the position of the tooltip according to the position of the mouse.

In the script tag, we have the data method that returns an object with the reactive properties and their initial values.

In the style tag, we have the styles for the container div to center its content horizontally and vertically.

We center the content horizontally with justify-content .

align-items set to center center content vertically.

display: flex enables flex layout which lets us use align-items and justify-content .

The div with ID tooltip has styles to set the border, padding, and makes the position absolute .

background-color is set to white to make the background white instead of transparent.

Now when we hover over the button, we see the tooltip displayed where the mouse pointer is.

Conclusion

We can create a tooltip easily with Vue 3 and JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *