Jaeger
Jaeger

Reputation: 1754

How do I increment a number only when hovering a div with VueJS?

I would like to create an easter egg, that will trigger if the visitor keeps his/her mouse on a text block for five seconds.

Here is my code:

<template>
 <!-- Some code -->
<div class="side-message" @mouseover="ee" @mouseleave="reset">
  <h1 v-if="easter" :class="easter ? 'ee' : ''">[ HYPE INTENSIFIES ]</h1>
  <p v-else v-html="replace($t('contact.intro'))"></p>
</div>
<!-- Rest of code -->
</template>

<script>
export default {
  data () {
    return {
      easter: false,
      seconds: 0,
      inside: false
    }
  },

  methods: {
    ee () {
      setInterval(() => {
        this.seconds += 1
      }, 1000)
      if (this.seconds >= 5 {
        this.easter = true
      }
      this.inside = true
    },

    reset () {
      this.seconds = 0
      this.inside = false
    }
  }
}

My issue is that this.seconds won't get incremented according to the Vue console, and I don't really understand why. Plus, this.inside also stays to false. But if I want to set a console.log() inside the function, it will be triggered without trouble.

What am I missing?

Thank you in advance

Upvotes: 0

Views: 130

Answers (1)

Kagiso Marvin Molekwa
Kagiso Marvin Molekwa

Reputation: 979

your code had some syntax errors and some weak logic.

try the following...

<template>
 <!-- Some code -->
<div class="side-message" @mouseover="ee" @mouseleave="reset">
  <h1 v-if="easter" :class="easter ? 'ee' : ''">[ HYPE INTENSIFIES ]</h1>
  <p v-else v-html="replace($t('contact.intro'))"></p>
</div>
<!-- Rest of code -->
</template>

<script>
export default {
  data () {
    return {
      timeInterval: null,  // to control the timeout alarm so that it doesn't run forever even when not needed
      easter: false,
      seconds: 0,
      inside: false
    }
  },

  methods: {

    // will stop incrementing seconds (if already running)
    stopTimer(){
        if (this.timeInterval)
          clearInterval(this.timeInterval);  
    },

    ee () {
      this.stopTimer();

      this.timeInterval = setInterval(() => {
        this.seconds += 1;
        if (this.seconds >= 5) {
            this.easter = true;
            this.stopTimer();
        }
      }, 1000);

      this.inside = true;
    },

    reset () {
      this.seconds = 0;
      this.inside = false;
      this.stopTimer();
    }
  }
}

Upvotes: 1

Related Questions