Discontinuing mouseover function until specified time has passed

In order to display a div when someone hovers over a text box for a second, without showing it if the mouse just quickly passes over the text box, the following JavaScript code can be used:

<input type="text" value="Fred" onmouseover="overit()">
<div id="dv" style="display:none">Jim</div>

var delay;
function overit()
{
delay = window.setTimeout('showme();', 1000);
}
function showme()
{
document.getElementById('dv').style.display = 'block';
}

If the gap between the mouseover and mouseout events is less than a second, the showme() function should not be called. To achieve this behavior without using jQuery, the provided solution can be implemented.

For a demonstration of this functionality, refer to the fiddle at http://jsfiddle.net/S4jx4/

Note that jQuery is not being utilized in this particular case.

Answer №1

Your suggested approach is getting close to a working solution. To improve it, consider incorporating an onmouseout event listener on the input element to stop the timeout.

<input type="text" value="Jenny" onmouseover="hoverFunction()" onmouseout="clearTimer();">

http://jsfiddle.net/YQ847/

Answer №2

When you are certain that the function will be executed after 1 second, there is no need to verify the time gap. Instead, focus on canceling the timeout when the mouseleave event occurs. Even if the function has already been called within the one-second timeframe, cancelling it will not have any adverse effects.

var delay;
function overit()
{
    delay = window.setTimeout('showme();', 1000);
}
function showme()
{
    document.getElementById('dv').style.display = 'block';
}
function leaveit() {
    window.clearTimeout(delay);   
}

<input type="text" value="Fred" onmouseenter="overit()" onmouseleave="leaveit()">
<div id="dv" style="display:none">Jim</div>

http://jsfiddle.net/hXE28/

Answer №3

Eliminate the inline JavaScript

<input type="text" value="Sara" id="txt" />
<div id="dv" style="display:none">Mia</div>

and implement event listeners

var input = document.getElementById('txt'),
    text  = document.getElementById('dv'),
    timer;

input.addEventListener('mouseenter', function() {
    timer = setTimeout(showText, 1000);
}, false);

input.addEventListener('mouseleave', function() {
    clearTimeout(timer);
}, false);

function showText() {
    text.style.display = 'block';
}

FIDDLE

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

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...

The system encountered an issue while trying to access the 'bannable' property, as it was undefined

message.mentions.members.forEach(men => { let member = message.mentions.members.get(men) if (!member.bannable) return message.reply(not_bannable) const reason = args.slice(1).join(" "); member.ban({reason: reason ...

Using Next.js API routes instead of relying on Axios for making API calls is a great

While following a tutorial, I encountered an issue with axios endpoints not working properly (resulting in a server error). Therefore, I am interested in learning how to utilize Next.js API routes in my project instead of axios. Any guidance on this matt ...

The React getTime() method does not properly update the state

I am attempting to update the state of the component Demoss using an external function called getTime(). My goal is to start updating the time in the state time when the page loads. In order to achieve this, I have called it in the componentDidMount meth ...

Trigger the original function again once the other function completes in jQuery AJAX

I'm working on improving my skills in jQuery, AJAX, and JSON. Within my application, there is a dropdown select menu: <select id="serviceload" name="serviceload"></select> The OPTIONS in the select menu are populated dynamically by anot ...

Why is $scope.$watch('$destroy') being called in Angular UI Router 1.0 even when not leaving the state?

Take a look at the plunker here. My understanding is that $scope.$watch('$destroy') should be invoked when $scope is on the verge of being destroyed. In the provided example, it seems that upon entering a state, the $scope.$watch('$destroy ...

JavaScript reference to a function

Although JavaScript is not my primary programming language, I decided to practice by attempting something simple - or so I thought ;) Below is the code I wrote: function Log () {} Log.format = function (func, facility, text) { func("hello"); }; Log ...

Setting up React Router in a nested directory with a flexible route structure

As a newcomer to react router, I am seeking guidance on setting it up in a specific scenario. Imagine we have a PHP application running on 'http://www.example.com'. Within this setup, there is a react application located at 'http://www.examp ...

Generate an HTML dropdown menu based on the item selected from the autocomplete input field

I have a PHP page that searches the database and returns JSON results to an autocomplete input field: https://i.sstatic.net/PPFgR.png When I display the response from the PHP file (as shown above), it looks like this: { "success": true, "results ...

Combining JavaScript functions and Vue.js methods through chaining

When working within a Vue component, I have a scenario where I am invoking a function from a separate JavaScript file. The requirement is to then trigger a method within my component once the first function has finished executing: Here is an example of my ...

Methods for establishing state within a React Native render function

I encountered an issue when attempting to set state within the render lifecycle. Warning: It is not recommended to update state during an ongoing state transition, such as in the render method or another component's constructor. The render method s ...

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

Component fails to re-render after token refresh on subsequent requests

Here is my axios-hoook.js file, utilizing the axios-hooks package. import useAxios from 'axios-hooks'; import axios from 'axios'; import LocalStorageService from './services/local-storage.service'; import refreshToken from &ap ...

Guide to dynamically swapping one SVG icon with another SVG icon using AngularJS

In my current setup, I am working with a dedicated framework that requires me to specify the path to an svg icon like so: <sit-command-bar sit-type="action" sit-layout="vertical"> <sit-command svg-icon="common/ ...

Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

Updating HighCharts with fresh data through Ajax

I'm currently in the process of replacing the highcharts that I initially loaded through ajax. The idea is to obtain new values from the user, pass them via Ajax, and then display an entirely new graph (with a different type and data). Here's wha ...

Is there a way to utilize JSON data to dynamically fill column names in a JQuery datatable?

JSON Data: { "data": [ { "name": "Garrett Winters", "designation": "Accountant", "salary": "$170,750", }, { "name": "Brielle Williamson", "designation": "Integration Specialist", "salary": "$372,000", } ] } H ...

I require assistance in obtaining the float value for the CSS property of 'font-size'

Can someone help me with retrieving the float value of the CSS 'font-size'? It works perfectly in Firefox, but I'm facing issues in Chrome, Safari, and IE. When trying to get this CSS value, it keeps converting to an integer instead of a flo ...