using vue.js to hide a div after a certain amount of time passes without the mouse hovering over it

Hello, I asked a similar question earlier but I've been stuck on this problem for quite some time.

I have a div that is set to v-show on specific events, such as when hovering over div1 and clicking on div2. I want to make it so this div disappears after a certain amount of time if the mouse hasn't touched it, let's say three seconds.

My issue is that I can't use v-on:mouseleave because the div appears without the mouse being on it. Therefore, I need something that will toggle v-show on the div after a delay has passed. Am I missing something? What should I be using in this case?

Thank you for your help!

Answer №1

To create a simple solution, you can utilize a component and incorporate an event listener within the mounted hook that utilizes a timeout to control a flag connected to v-show. This way:

Vue.component('my-deiv', {
  template: `<template id="block"><div v-show="show">A div</div></template>`,
  mounted(){
    this.$el.addEventListener('mousemove', () => {
      setTimeout( () => {
        this.show = false;
      }, 3000)
    })
  },
  data(){
    return{
      show: true
    }
  }
});

Whenever the mouse moves over the div, it triggers the timeout functionality. To see it in action, check out the JSFiddle link provided: https://jsfiddle.net/nb80sn52/

UPDATE

If your intention is to hide the div only when the mouse remains idle on it for a specific duration, without triggering when the mouse exits, you can reset the timeout with each mouse movement and cancel it completely upon mouse leave. Here's the revised version:

Vue.component('block', {
  template: "#block",
  mounted() {
    this.timer = null;

    this.$el.addEventListener('mousemove', () => {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.show = false;
      }, 3000)
    })

    this.$el.addEventListener('mouseleave', () => {
      clearTimeout(this.timer);
    })
  },
  data() {
    return {
      show: true
    }
  }
})

You can view the updated functionality in action through this JSFiddle link: https://jsfiddle.net/utaaatjj/

Answer №2

To make your component disappear after a set amount of time, consider using the setTimeout function within your render function or any other relevant function. This can be achieved by setting this.visible = true to this.visible = false once the specified time has elapsed.

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

What sorcery does Facebook use to alter the URL without triggering a page reload?

Similar Question: How can I update window location without a reload and # hack? Facebook and Ajax What method does Facebook use to change the URL without reloading the page? In the past, Facebook utilized the hash (#) symbol to prevent the page f ...

Can the w regular expression pattern be modified to include special characters like é? If not, what other options are available?

Imagine having a regular expression that appears as follows: \w+ In this case, the string "helloworld" would be accepted: helloworld However, "héllowörld" would not pass the test: héllowörld The regex will stop at é (and also break atö) ev ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

Encountering an issue while trying to compile my Angular 6 project - an ERROR keeps

Upon initiating my project with ng serve, I encountered a troublesome error. Despite updating my TypeScript, the issue persisted. Here is the detailed error message: ERROR in node_modules/@types/node/assert.d.ts(3,68): error TS1144: '{' or ...

Eliminating characteristics and rejuvenating the component

I have divs on my webpage that I want to keep hidden until a specific element is clicked. When trying to hide them, I encountered three options: visibilty: hidden - I didn't like this because the hidden div still took up space in the layout. displa ...

issue with webpack-dev-server not refreshing after changes to HTML or Sass files

Here is the layout of my project: \root \webpack.config.js \public \ index.html \ ... \ css \ directives \ views \ dist (webpack output) \app.js ...

Experiencing difficulties when attempting to send a cookie to the server

Why is the vue+axios frontend not sending cookies to my php server in the request header? I am currently in the process of migrating an old project to a new server. After making some optimizations to the project architecture, everything worked perfectly f ...

Retrieve the specified columns as per user-defined filters

Being completely new to JavaScript, I have been assigned the task at hand. The technology stack includes node.js, express, mongodb, and mongoose. Imagine that the database/collection(s) consist of 1000 rows and each row has 50 columns. Some columns may h ...

Error message "Unable to access property 'rotation' of an object that does not exist - Three.js"

I'm currently facing an issue where my code is executing as expected, but there are two errors popping up in the console saying "Cannot read property 'rotation' of undefined". It's puzzling because both variables are defined globally. I ...

When using Vue.js, I notice that the files are only found once the "dist" folder is added

I am currently working on a project using the vue js framework. Once I finish building the project, I end up with various files in the following structure: dist --index.html --assets --style.css --script.js However, when I try to start the server with ...

Unable to access a frame inside an iframe and frameset using JavaScript when both domains are identical

I am attempting to use JavaScript to access an HTML element within a nested frame in an iframe and frameset. The structure of the HTML is as follows: <iframe id="central_iframe" name="central_iframe" (...)> <frameset cols="185, *" border="0" ...

React is indicating that returning functions is not appropriate as a React child. This issue may arise if you accidentally return a component instead of <Component /> within the render method

Check out the main game.js and app.js files: //Here is the code in game.js// import React, { Component } from "react"; class Game extends Component { constructor(props) { super(props); this.state = { num: 0 }; this.numPicker = this.numPi ...

What is the reason that the variable is not accessible after the switch block?

While working on my code, I encountered a dilemma. I needed to print the value of the 'text' variable after a switch block. However, I mistakenly did not include an expression in the switch statement which caused it to skip the default case and t ...

What options are available for labels in Bootstrap v5.0.0-beta1 compared to BS 3/4?

How can I use labels in Bootstrap v5.0.0-beta1? In Bootstrap 3, the labels are implemented like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" /> <span class="label label-success ...

When working with express.js, the following error may occur: Uncaught Error [ERR_HTTP_HEADERS_SENT]: Unable to modify headers after they have been sent to the client

Seeking assistance for resolving this issue. The purpose of this code is: Update the artist using the specified artist ID and data from the request body, then save it to the database. Return a 200 response with the updated artist in the response body. If ...

"Changing a Java script base addon file to a customized addon in Odoo 16: A step-by-step guide

Here is the JavaScript file located in the "documents" enterprise base addon: I want to include the field "document_type_id" in the export const inspectorFields = [] array through a custom addon. /** @odoo-module **/ import { device } from "web.confi ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...

Testing the $resource function invoked by Karma Jasmine within a controller

I am facing challenges with implementing Karma to test API calls. Below is the test file provided: describe('Requests controller test', function() { beforeEach(module('balrogApp.requests')); var ctrl, scope; var requestData = [ ...

Ways to mimic an Angular directive with a required field

Recently, I encountered a challenge that involves two directives: directive-a, directive-b. The issue arises because directive-b has a `require: '^directive-a' field, which complicates unit testing. In my unit tests, I used to compile the direc ...