Myzifer
Myzifer

Reputation: 1125

How to use jquery to time how long it take between actions of on the page (stopwatch between button clicks)

My aim is to time how long it take a user to navigate through a bunch of pages(hidden divs on single page) so I can record time taken preferably in mm:ss or just sss.

I would start from a input button which should start the timer and then upon click of another button on 1 of the hidden divs it will stop the timer.

End goal would be to have 3 timers on the same page and it has to be via jquery or w/e else can be used to time between 2 different buttons being clicked.

I know how it can be done in the controller but as I need to collect 3 separate times and can't have it being done over 3 separate actions/db saves.

So far all I've found is reference to you having already set a time on it and then that acts as a countdown rather than a stopwatch.

Any help would be much appreciated.

Upvotes: 0

Views: 739

Answers (2)

Jasper
Jasper

Reputation: 76003

$(function () {

    //cache the time when `document.ready` fires and create a variable to track clicks
    var startTime = new Date().getTime(),
        clicks    = [];

    //only bind the `click` event handler to elements with the `my-links` class so we don't track every click on the webpage
    $('.my-links').on('click', function () {

        //push an object onto the tracking array that includes the target of the link and the time when it was clicked
        clicks.push({ time : new Date().getTime(), target : $(this).attr('href') });
    });
});​

Here is a demo: http://jsfiddle.net/wwnyY/1/

You can then iterate through your array of saved clicks, or send it to a server-side script to store for later use.

Here are some good docs for Date(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074949

You don't need jQuery for this. You can get the current milliseconds-since-The-Epoch value like this:

var ms = new Date().getTime();

Or if character-counting is your thing:

var ms = +new Date();

Just do it twice and subtract the first from the second. The only place jQuery might be involved would be hooking the clicks on the buttons, e.g.:

$("selector_for_button").click(function() {
    // ...your code here...
});

Upvotes: 1

Related Questions