-2

I want to show a tootip when an element is hovered for 2 seconds or more. How can I do it?

nilesh_ramteke
  • 135
  • 3
  • 8

3 Answers3

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
  • @user3552391 Then just use to code and adapt it to your need – Weedoze Jan 13 '17 at 12:16
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