el Dude
el Dude

Reputation: 5183

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?

Upvotes: 1

Views: 2695

Answers (4)

el Dude
el Dude

Reputation: 5183

Ok, I did some trick with dynamic id and this is what came out:

<b style="color:red;" onclick="if(this.style.color!='green'){return false;}else{this.style.color='red';} alert(this.parentNode);" onmouseover="if(this.style.color!='green'){var newID='tmpID_'+Math.floor(Math.random() * (10000000)); if(this.id==''){this.id=newID;} setTimeout('top.document.getElementById(\''+this.id+'\').onclick();',1000); this.style.color='green';}" onmouseout="this.style.color='red';">click</b>

crossbrowsered =)

Upvotes: 0

user1726343
user1726343

Reputation:

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);
});

Upvotes: 2

Eee
Eee

Reputation: 179

You'll have to do some extra work, and this won't work out very well for you inside of inline Javascript. This is all pseudocode so I don't recommend copy/pasting!

// We'll need to create an interval and store it
var timerInterval = {}
// And keep track of how many seconds have elapsed   
var timeElapsedInSeconds = 0;

function tick (){
   timeElapsedInSeconds++;
   if (timeElapsedInSeconds > 0){
       // YOUR GREAT CODE HERE
   }
   // Either way, let's be sure to reset everything.
   resetTimer();
}

function hoverOverHandler (){
   // Start our timer on hover 
   timerInterval = window.setInterval(tick, 1000);    
}

function resetTimer () {
   timeElapsedInSeconds = 0;
   window.clearInterval(timerInterval);
}

function hoverOutHandler () {
   // Kill timer on hoverout
   resetTimer();
}

Upvotes: 1

CKK
CKK

Reputation: 909

You should start the interval on mouse over event as a global variable to refer on mouse out event to clear it like @Asad said.

<b onclick = "alert()"
 onmouseover = "window.countdown = setTimeout(function(){this.click();}, 1000);"
 onmouseout = "clearTimeout(countdown)">
 123
</b>

Upvotes: 1

Related Questions