javascriptjqueryhtmlif-statementjquery-hover

how to add if condition for mouseover (cursor) exceeds three scond in a "a tag"?


My question is not a time duration of animation. My question is - If mouse is stay more than 3 second in TAG. Hover effect will come, but never load the data before 3 second. So load the data after 3 seonds only. From my end below are my html code and i can't add class name and id name because all are dynamic

Html:

 <a href="#" style="display: inline !important; cursor:pointer;">
   <div onmouseover="Snapshot("some backend data")"></div>
</a>

This type of structure i am looking.

if (time >= 3000s)
{
add data
}
else
{
add another
}

Solution

  • You want to create a function for the mouseover event that starts a timer. If that timer reaches 3000ms, or more, then call the function to update whatever it is you are updating.

    Also create a mouseout event that clears the timeout.

    <a href="#" onmouseover="snapshot('some backend data')" onmouseout="clearSnapshotTimeout()">Move your cursor and wait 3 seconds</a>
    
    var snapshotTimeout;
    
    // code that deals with (loads) data here.
    function snapshot(data) {
        snapshotTimeout = window.setTimeout(function() {
            alert('alert happens after 3 seconds');
        }, 3000);
    }
    
    function clearSnapshotTimeout() {
        window.clearTimeout(snapshotTimeout);
    }
    

    EDIT:
    If you cannot add a mouseout event to the html pages then you could try this:

    <a href="#" onmouseover="snapshot('some backend data')">Move your cursor and wait 3 seconds</a>
    
    var snapshotTimeout;
    // code that deals with (loads) data here.
    function snapshot(data) {
        snapshotTimeout = window.setTimeout(function() {
            alert('alert happens after 3 seconds');
        }, 3000);
    }
    
    function clearSnapshotTimeout() {
        window.clearTimeout(snapshotTimeout);
    }
    
    // add the mouseout event handler to each element that has a mouseover attribute.
    var mouseOverElements = document.querySelectorAll('[onmouseover^="snapshot("');
    
    for(var i=0;i<mouseOverElements.length;i++) {
      console.log(mouseOverElements[i]);
        mouseOverElements[i].onmouseout = function() {
            clearSnapshotTimeout();
        }
    }