views:

156

answers:

4

I want to start a timer when the user clicks on a object, and stop it when the user releases the click. All using javascript/jquery.

A: 

The following should get you started

var start_time;
function start() {
    start_time = new Date();
}
function end() {
    var now = new Date();
    alert(now-start_time);
}

$('#element_id').mousedown(start);
$('#element_id').mouseup(end);

the mousedown event will run the start function which sets the start time. the mouseup event will substract the start time from the current time. The result is in milliseconds

Jonathan Fingland
that's what i want. Thank you
EduardoMello
And you might want to add the mouseout(), to display the difference in time, in case the user drags the mouse outside the element before releasing. Or set the mouseup() on the document, and have a flag to make sure the mouse was clicked inside the element. This way it doesn't matter where the user releases the mouse button...
peirix
@peirix Hey! I said that first ;) +1 to you.
Jonathan Sampson
A: 
function myTimer() {
    doSomething();
}

$('#thing').mousedown(function() {
    $(this).data('timerHandle', setTimeout(myTimer));
});
$('#thing').mouseup(function() {
    clearTimeout($(this).data('timerHandle'));
}
chaos
I would use .data rather than custom attributes that leak in ie
redsquare
Yeah, good idea. Editing per.
chaos
A: 

$("#element").mousedown(); will let you record when the user clicks, and similarly $("#element").mouseup();will let you record when the button is released.

var start = 0;
$("#element").mousedown(function() { start = new Date(); });
$("#element").mouseup(function() {
    var cur = new Date();
    alert(cur-start);
}
peirix
Watch out for users who mousedown on the element, and then pull the mouse off the element before releasing.
Jonathan Sampson
A: 

link to jquery plugin of timer http://plugins.jquery.com/project/timers

Haim Evgi