Pass milliseconds from timer to input on form submit with jQuery Stopwatch

I am attempting to get the milliseconds value from this jQuery Stopwatch library https://github.com/robcowie/jquery-stopwatch

The millisecond value is not documented, apart from in a GitHub issue that states

Read More

Make elapsed milliseconds available in data. #2 …
Get at it with $().data(‘stopwatch’)[‘elapsed’]

I have attempted to access the milliseconds in this way through the following code (it’s within WordPress, hence the lack of $ signs)

<a href="#" id="test"><h2>Test</h2></a>
<script>
    jQuery( "#test" ).click(function() {
        alert(jQuery().data('stopwatch')['elapsed']);
    });
</script>

But I am getting the following console error

Uncaught TypeError: Cannot read property ‘elapsed’ of null

The stopwatch is initialised through this code

jQuery( document ).ready(function($) {
    setTimeout(function(){ $('.quizTimerSpan').stopwatch({startTime: 0, format: '{MM}:{ss}'}).stopwatch('start') }, 8500);
});

The first problem is actually getting the millisecond value, and then actually passing it through to an input value on a button click. I assume the following code will work once I actually get the millisecond value, but I’m pretty new to jQuery so would be good to get this sanity checked as well.

jQuery( "#question" ).submit(function( event ) {
      jQuery( "#timerValue" ).val(.data('stopwatch')['elapsed']));
      event.preventDefault();
});

HTML form element…

<input type="hidden" name="timerValue" id="timerValue" value="" />

Related posts

Leave a Reply

1 comment

  1. I have managed to achieve what I wanted to do by switching to the jQuery Timer library from here http://jchavannes.com/jquery-timer/demo

    The following code did exactly what I needed…

    function pad(number, length) {
        var str = '' + number;
        while (str.length < length) {str = '0' + str;}
        return str;
    }
    function formatTime(time) {
        time = time / 10;
        var min = parseInt(time / 6000),
        sec = parseInt(time / 100) - (min * 60),
        hundredths = pad(time - (sec * 100) - (min * 6000), 2);
        // Switch for more accurate output
        // return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
              return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2);
    }
    
    var quizStopwatch = new (function() {
        var $stopwatch;
        var incrementTime = 70;
        var currentTime = 0;
    
    $(function() {
        $stopwatch = $('.quizTimerSpan');
        quizStopwatch.Timer = $.timer(updateTimer, incrementTime, true);
    });
    
    function updateTimer() {
        var timeString = formatTime(currentTime);
        $stopwatch.html(timeString);
        currentTime += incrementTime;
        document.title = timeString;
        $("#timerValue").val(currentTime);
    }
    });
    

    As a bonus, I am also able to set the title of the page on each interval.