Measure hover time on a flipcard HTML

91 Views Asked by At

I have designed 4 flip cards in HTML which work on hover using css. My goal is to measure the time spent hovering on each flip card. I tried onmouseover event but cannot figure it out. How can this be done? Any hints will be appreciated.

1

There are 1 best solutions below

0
anathrax On

You could run a function on the "mousenter" event and save the time in the startDate variable. Then on "mouseleave" subtract the new time from the old time in milliseconds. Then just convert milliseconds to seconds and log the result.

You can read more about Date in this article.

Also take in note that here I used div just as an example. You can modify the code as you want.

// declare a hover box/card
const card = document.getElementById("card")

card.onmouseenter = () => {
    start();
}
card.onmouseleave = () => {
    end();
}

// save your start and end time
let startDate;

let endDate;

function start() {
    startDate = new Date();
}

function end() {
    endDate = new Date();
    let millis = endDate - startDate;
    console.log(millis / 1000 + " seconds");
}
<!DOCTYPE html>

<html>

<head>
    <title>Timer</title>
    <script src="./main.js" defer></script>
</head>

<body>
    <!-hover over and out of the box and see what happens-->
    <div id="card" style="width: 50px; height: 50px; background-color: red;"></div>
    <canvas></canvas>

</body>

</html>