Home > Enterprise >  Custom tooltip with Vue acts weird after clicking on button two or three times
Custom tooltip with Vue acts weird after clicking on button two or three times

Time:01-01

I made that code to develop a custom tooltip that auto-closes after 2 seconds from user clicking on a button. I want it to work only on click not hover .

It works well for the first two times but then it acts weird when I click on it again.

You can check it here

<template>
  <div id="app">
    <button @click="copyThat" > 
    copy that 
    <div  v-if="copied"> copied </div>
    </button>
    
  </div>
</template>

<script>

export default {
  data(){
    return{
      copied: false
    }
  },
  methods: {
    copyThat: function (){
      this.copied = true;
      setInterval( () => {
        this.copied = false;
      }, 2000 )
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.relative-button{
    position: relative;
}
.tooltip{
    position: absolute;
    top: 130%;
    padding: 1rem;
    left: -50%;
    background: rgba(0,0,0,0.5);
    color: white;
    font-weight: bold;
    z-index: 100;
    width: 113px;
    height: 30px;
    border-radius: 4px;
    padding: 7px;
    text-transform: capitalize;
    font-weight: 400;
    font-size: 13px;
}
</style>

CodePudding user response:

Use setTimeout instead:

copyThat: function() {
  this.copied = true;
  setTimeout(() => {
    this.copied = false;
  }, 2000);
}

CodePudding user response:

The problem is you doesn't clear the interval you created so once you click the copy button, it will create one new interval and several intervals will executing every 2 seconds which make your toolbar become very weird.

You could either use setTimeout or use window.clearInterval to clear all the interval before creating a new one.

  • Related