I want to show a tootip when an element is hovered for 2 seconds or more. How can I do it?
Asked
Active
Viewed 3,489 times
-2
-
1Pick the time when you enter, pick the time when you exit, then take the difference? – Tolga Evcimen Jan 13 '17 at 10:40
-
Show me your code. what you tried till now? – keerti Jan 13 '17 at 10:42
-
I want to show a tootip when an element is hovered for 2 seconds or more. How can I do it? – nilesh_ramteke Jan 13 '17 at 10:46
3 Answers
4
var startTime, endTime;
function handlerIn() {
startTime = new Date();
}
function handlerOut() {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff % 60);
console.log("hover during " + seconds + " sec");
}
.hover {
background-color: red;
width: 100px;
height: 100px;
}
<div class="hover" onmouseenter="handlerIn()" onmouseleave="handlerOut()">HOVER ME</div>
<div id="seconds"></div>

Weedoze
- 13,683
- 1
- 33
- 63
-
This will not work for me beacuse I want to show the tooltip if the mouse is there over an element for more than 2 seconds. Not when mouseleave event is fired. – nilesh_ramteke Jan 13 '17 at 12:11
-
1
You can use setTimeout() method with onmouseover and onmouseout events.
Tooltip css: http://www.w3schools.com/howto/howto_css_tooltip.asp
setTimeout method: http://www.w3schools.com/jsref/met_win_settimeout.asp
<div id="example" class="tooltip" onmouseover="start()" onmouseout="stop()">example text</div>
let t, hoverTime=2000;
function start(){
t = setTimeout('showTooltip()', hoverTime);
}
function showTooltip(){
let node = document.createElement("span");
let textnode = document.createTextNode("Tooltip text");
node.className='tooltiptext';
node.appendChild(textnode);
document.getElementById("example").appendChild(node);
}
function stop(){
clearTimeout(t);
if(document.getElementById("example").childNodes[1]){
document.getElementById("example").removeChild(document.getElementById("example").childNodes[1]);
}
}

Iosu
- 213
- 7
- 14
0
You can check the enter time and exit time with onmouseenter="fn()"
and onmouseout="fn()"
. Here's a simple way to do it and it also displays the time in miliseconds!
var time = 0;
var hover = 0;
var out = 0;
function getInTime() {
hover = Date.now();
}
function getOutTime() {
out = Date.now();
time = out-hover;
document.getElementById('time').innerHTML = " Show hover time: " + time + 'ms';
}
<button onmouseout="getOutTime()" onmouseenter="getInTime()" >Hover Here</button>
<br /><br />
<button id="time">Hover Time</button>

Razvan Alex
- 1,706
- 2
- 18
- 21