Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many seconds did the user hover an element using jquery or javascript?

just need a little help here. My problem is, how can I count the seconds when i hover a specific element. Like for example when I hover a button, how can i count the seconds did i stayed in that button after I mouseout?

like image 378
rochellecanale Avatar asked Jul 20 '26 01:07

rochellecanale


2 Answers

An alternate solution using setInterval. DEMO HERE

var counter = 0;
var myInterval =null;
$(document).ready(function(){
    $("div").hover(function(e){
        counter = 0;
        myInterval = setInterval(function () {
            ++counter;
        }, 1000);
    },function(e){
        clearInterval(myInterval);
        alert(counter);
    });
});
like image 107
Anupam Avatar answered Jul 22 '26 13:07

Anupam


A simple example

var timer;
// Bind the mouseover and mouseleave events
$('button').on({
    mouseover: function() {
        // set the variable to the current time
        timer = Date.now();
    },
    mouseleave: function() {
        // get the difference
        timer = Date.now() - timer;  
         console.log( parseFloat(timer/1000) + " seconds");
        timer = null;        
    }
});

Check Fiddle

like image 23
Sushanth -- Avatar answered Jul 22 '26 15:07

Sushanth --



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!