Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up:

<div @mouseover="trigger"></div>

In the script section:

data() {
    return {
        hovered: false
    }
}

methods: {
    trigger() {
        setTimeout(function(){ this.hovered = true }, 1000)
    }
}

My issue lies in understanding the scope within Vue. The 'hovered' variable is not recognized within the function, causing errors. Any suggestions on how to resolve this?

Answer №1

Did you consider utilizing an arrow function within your setTimeout? This will preserve the context of this.

data() {
    return {
        isHovered: false
    }
}

methods: {
    initiateHover() {
        setTimeout(() => { this.isHovered = true }, 1000)
    }
}

Answer №2

<div @mouseover="triggerOverEvent" @mouseleave="resetOverEvent "> events </div>



data: () => {
    return {
      mouseOverCount: 0
    }
  },
methods: {
    triggerOverEvent () {
      this.mouseOverCount++
      if (this.mouseOverCount < 2) {
        this.showPopup()
      }
      console.log(this.mouseOverCount)
    },
    resetOverEvent () {
      this.mouseOverCount = 0
      console.log('reset')
    },
}

Answer №3

Code to display content upon hovering for 1 second, and then hide it when no longer hovered.

<span @mouseover="activate" @mouseleave="deactivate">Hover over me!</span>
<div v-if="display">...</div>

data() {
   return {
      display: false;
      isHovering: false,
   };
},
methods: {
    activate() {
       this.isHovering = true;
       setTimeout(() => this.display = this.isHovering, 1000);
    },
    deactivate() {
       this.isHovering = false;
       this.display = false;
    },
}

Answer №4

Trying to tackle the issue of selecting items in a list only when the user hovers for a certain amount of time (to prevent menu flickering)

Pug template:

.div(
    @mouseover="select(identifier)"
    @mouseout="clear()"
) {{content}}

Data:

hovered: false
selectedId: ""

Along with the following methods:

select(identifier) {
    this.selectedId = identifier
    setTimeout(() => {
        if(this.selectedId === identifier )
            this.hovered = true
        },
        1000
    )
},
clear() {
    this.selectedId = ''
}

The strategy involves verifying if the item being hovered on by the user is the same as the one from a second ago.

Answer №5

To utilize outdated syntax, ensure 'this' is bound to the setTimeout function

data() {
    return {
        highlighting: false
    }
}

methods: {
    activate() {
        setTimeout(function(){ this.highlighting = true }.bind(this), 1000)
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Text that disappears upon clicking on show/hide按钮

Could someone please help me figure out how to prevent the "See more" text from disappearing when clicked in the example below? I want it to stay visible. Thank you! ...

The functionality for accessing objects in Chrome Developer Tools is not functioning properly

Every time I attempt to access an object in Chrome Developer Tools, I encounter the following error message: VM4939:1 Uncaught TypeError: Cannot read property 'cells' of undefined at :1:13 Here is my code: <head> <script> ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

"Despite the successful execution of the PHP script, the error function in the Ajax POST request

I am working on developing a mobile app using jQuery, jQuery Mobile, and HTML with PhoneGap. I have successfully implemented AJAX to call PHP scripts on the server for tasks like updating, inserting data, and sending emails. However, I consistently encoun ...

Sequelize: When attempting to use .get({plain: true})) method, an error is returned indicating that .get is

I'm facing a strange issue as I am able to retrieve only the values of an instance in other parts of my code without any problems. Can you spot what might be wrong with my current code? app.get('/profile', checkAuth, function(req, res) { ...

Implement AngularJS to ensure that scripts are only loaded after the page has finished rendering

I am having trouble implementing the TripAdvisor widget on my website. It functions correctly when the page is refreshed, but it does not appear when navigating through links. Additionally, an error message is displayed stating that the document could not ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Customize hover effects in tailwind css with dynamic values

I am trying to customize the text color on hover based on different category names using tailwind CSS. In my configuration, I have assigned a specific color code for each category like this : tailwind.config.js theme: { extend: { } }, co ...

"The issue of Django showing a 'select a valid choice' error when trying to populate a select field

I encountered a validation error while trying to create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) After populating the ...

gathering identical objects in the collection

I need to calculate the total time of the specified objects and display it in a single list. Here is the object data: var list = [ { 'user': 'Tom', time: 270547 }, { 'user': 'Alex', time: 82081 }, { 'user&apo ...

Unable to modify the value of an object variable generated from a query in JavaScript, ExpressJS, and MongoDB

Here is the code snippet I've been working on: let addSubmissions = await Submission.find({"type": "add-information"}, (err) => { if(err) { console.log(err) req.flash('error', 'No "add submissions" were found&apo ...

Store the selected checkbox values in an array when submitting in Ionic

One issue I am facing is that the checked checkboxes are returning true instead of the value of input (type="checkbox"). Array displaying responded checked or unchecked items I am unable to store this data in an array as needed. Additionally, I cannot sp ...

Is there a way for me to discover the top trending photos on Instagram today?

Finding information on the Instagram API can be quite challenging due to poor documentation. Is there a method available to discover the most liked Instagram photos by location, such as identifying the top picture liked by Danish users today? Any insight ...

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

How can you assign a default value in a React select dropdown and dynamically add the remaining values?

I'm currently developing a React application that includes a form with a select dropdown feature. My goal is to have the 'uom' field value from the selected product record automatically set as the default option in the dropdown when the user ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...

Determine when the scrollbar of a DIV has reached the bottom using Vue.js

Just starting out with Vuejs and I could use some guidance. Can anyone please advise on how to trigger a message when a div in Datatable vuejs reaches the bottom of its page? Any help would be greatly appreciated. https://i.sstatic.net/jKfRT.jpg https://i ...

Understanding the error handling in Express.js

Learning about error handling in express is new to me and I have a straightforward piece of code like this - const express = require('express'); const MongoClient = require('mongodb').MongoClient; const app = express(); let url = &a ...

After exporting static HTML, the links in Next.JS seem to become unresponsive

Exploring the world of NEXT.JS for the first time and encountering challenges with deploying a static site. In my component Nav.tsx, I have the following structure: const Nav = () => { return ( <nav className='nav p-3 border-bottom&a ...