Search code examples
javascripthtmleventsonmouseoveronmouseout

onmouseover() to invoke onclick after 1 second?


I have an element:

<b onclick="alert('');" onmouseover="this.style.color='red'; setTimeout('........', 1000);" onmouseout="this.style.color='';">123</b>

I need that when element is mouseovered and after 1 second the mouse cursor continue staying above this element, then onclick() event of this element should start.

In other words, what should be instead of '..............' in onmouseover() event?


Solution

  • window.countdown = setTimeout(function(){this.click();}, 1000);
    

    Additionally, you need to clear the interval in the mouseout handler:

    clearTimeout(countdown);
    

    Ideally you would give your element an ID and use the new event registration model:

    var e = document.getElementById('myelement');
    e.addEventListener('click',function(){
        alert('');
    });
    e.addEventListener('mouseenter',function(){
        var self = this;
        this.style.color='red';
        window.countdown = setTimeout(function(){self.click();}, 1000);
    });
    e.addEventListener('mouseleave',function(){
        this.style.color='';
        clearTimeout(countdown);
    });