Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops moving within the div.

HTML

<div class="tooltip"><p></p></div>
<div class="holder" id="1"></div>
<div class="holder" id="2"></div>

CSS

.holder{
    display: block;
    float: left;
    margin-bottom: 0.25%;
    width: 100%;
    height: 200px;
    cursor: pointer;
    border-top: 1px solid rgb(100, 100, 0);
    border-bottom: 1px solid rgb(100, 100, 0);
}
.tooltip{
    position: absolute;
    display: none;
    width: 150px;
    background-color: white;
    z-index: 5;
}

JS

var holder = document.getElementsByClassName("holder");
var tooltip = document.getElementsByClassName("tooltip")[0];
for(var i = 0; i < holder.length; i++){
    var moving;
    holder[i].onmouseover = function(ev){
        moving = false
        tooltip.style.display = "block";
        tooltip.style.top = ev.clientY;
        tooltip.style.left = ev.clientX;
    }
    holder[i].onmouseout = function(ev){
        moving = false
        tooltip.style.display = "none";
        tooltip.style.top = ev.clientY;
        tooltip.style.left = ev.clientX;
    }
    holder[i].onmousemove = function(ev){
        moving = true;
    }

    if(moving){
        tooltip.style.display = "none";
        tooltip.style.top = ev.clientY;
        tooltip.style.left = ev.clientX;
    }
}

Answer №1

An inexperienced method would involve setting a timer when the onmousemove event is triggered. Once the timer runs out, execute the hiding function. Upon the next onmousemove event being triggered, reset the timer.

Determining when a user has stopped moving their mouse is a subjective decision for the application to make. In reality, each movement of the mouse equates to a separate mouse move event per pixel traveled.

This process requires some level of intelligence due to the frequent triggering of the onmousemove event. Consider implementing something similar to the following:

var mouseStartedMoving = false;
var mouseMoved = false;
const MINIMUM_MOUSE_MOVE_TIME = 100;

setInterval(() => { 
   if(!mouseMoved && mouseStartedMoving) {
       //Mouse stopped moving
       //Implement CSS change
       mouseStartedMoving = false;
   }
   mouseMoved = false;
}, MINIMUM_MOUSE_MOVE_TIME);

holder[i].onmousemove = function(ev){
  mouseStartedMoving = true;
  mouseMoved = true;
}

Answer №2

To achieve this result, utilize the "setTimeout" method.

While monitoring mouse movements, update the value of "mouseMoved" with the current time in milliseconds. Then implement the following code snippet:

setTimeout(function(){ 

    var currentTime = new Date();
    var currentMillis = d.getMilliseconds();
    var timeDifference = currentMillis - mouseMoved;
    if (timeDifference > 3000)
        alert("The mouse has been stationary for 3 seconds"); 
}, 3000);

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

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...

Transferring information between a service and a controller

I'm struggling to pass data between a service and a controller in my AngularJS project. Even though I've followed the recommended steps, the code is not functioning as expected. Below is the controller snippet: function udpController($scope ...

Waiting for the initial render before using document.getElementById() in next.js

I followed a tutorial that demonstrates how to access a canvas element by id using plain JavaScript. The tutorial can be found here. In the video, the method is explained around 5:10 and I adapted it for next.js in the code snippet below. import React, { u ...

Showcasing a single item per row in carousels on small and medium-sized devices

I have successfully implemented a Bootstrap carousel to display 3 items in a row, which is working well. However, I am looking to modify it so that only one item is shown on smaller devices such as mobiles or tablets. Can anyone assist me with this? Belo ...

Switching from ejs format to html

I've been working on a tutorial that uses ejs, but I'm not too familiar with it. I'd like to know how to convert the server.js from using ejs to html. Here's the code snippet: app.set('view-engine', 'ejs') app.use( ...

Need a module from the main directory

Imagine having these folders: 'C:\\src' // Main directory. 'C:\\src\\inner1' // Contains 'a.js' 'C:\\src\\inner2\\innermost' // Contains 'b.js' ...

Why is it that the z-index doesn't seem to affect the stacking order of my background image?

I am facing an issue with my Bootstrap carousel where the z-index is not working as expected. The decoration I have in the background is overlapping the text instead of appearing behind it. I want the illustration to be positioned under the text. .carou ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...

Angular-ui typeahead feature allows users to search through a predefined

I recently developed a typeahead feature using the angular-ui library. Here is the current HTML for my typeahead: <input name="customers" id="customers" type="text" placeholder="enter a customer" ng-model="selectedCustomer" uib-typeahead="customer.fir ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...

Using socket.io to listen for events and wait for promises to resolve

I am facing an issue with a button that communicates with the server to verify if a value entered in an input box already exists. The current code is as follows: $("#button").click(function () { var exists = false; var name = $("#name").val(); ...

Exploring parameterized routing in Node.js and Express

I am currently facing an issue with my node.js API where I have two separate routes set up. One route is for retrieving user data by ID, while the other is a general user endpoint. Here are the routes: app.get('/api/v1/user/:userid', function (r ...

The system cannot locate the module: Unable to find '@reactchartjs/react-chart-2.js'

I've been working on implementing this chart using the npm module called react-chartjs-2. I followed these steps to install the module: Ran the command: npm install --save react-chartjs-2 chart.js As a result, my package.json file now looks like th ...

What is the best way to incorporate a JavaScript file into my ejs file using node.js?

As I work on creating a website for my school project, I encountered a challenge involving including CSS files in node.js. Thankfully, after researching on stackoverflow, I was able to find a solution. Now, I am facing another issue - how to include a java ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

"Unusual HTML and jQuery quirk causing a perplexing issue: a function that keeps looping inexp

A unique code written in javascript using jQuery allows users to create a "box" on a website with each click of a button, triggering an alert message upon clicking the box. The process is as follows: 1) Clicking the "Add (#addBox)" button appends a new li ...

Align image within box using Bootstrap

My project screenshot is displayed below. The red line separates the current state from the desired outcome. I am struggling to make it fullscreen, meaning it should extend all the way to the corners. Despite trying various methods with Bootstrap 4, I have ...

Encountering a problem when making a HTTPS GET request to a REST API using

I am currently running an Angular application that utilizes an external API to fetch country ISOs. However, I am encountering an error with the API since it uses HTTPS. Interestingly, when I implement a proxy in my Angular local environment by mapping /is ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Utilizing D3.js to selectively apply the nest.key() function to certain elements within an array

I have a CSV file containing hierarchical tree data as shown below: industry,level1,level2,level3,name Ecommerce,Web,,,Rakuten Ecommerce,Crowdsourcing,,,Lancers Social,Photo sharing,Deco apps,,Snapeee Social,Photo sharing,Deco apps,Collage apps,DecoAlbum ...