jQuery: event duration times

Suppose that you want to implement a jQuery version of an arcade platform game. When the hero jumps from one platform to another, you have to find a way to calculate the time elapsed from the pressure of the mouse button (or a keyboard key) and its release in order to make the hero jump higher or lower, depending on the mouse pressed duration time. Here's how you can do with jQuery:

$(function() {

  var down = 0;

  $('#test').bind('mousedown mouseup', function(event) {
  
  
    var evtType = event.type;
    
    switch(evtType) {
    
      case 'mousedown':
      
        var interval = setInterval(function() {
        
        
          down++;
        
        
        
        }, 1000);
        
       break;
       
      case 'mouseup':
      
        clearInterval(interval);
        
        alert('You have pressed the mouse button for ' + down + ' seconds');
        
       break;
       
       
      default:
        break;
    
    
    
    }
  
  
  
  });


});

The technique described in the code above can be applied to other events as well (e.g. keydown and keyup, etc.) and it makes use of a timer created when a user clicks and holds the mouse button and subsequently deleted when the mouse button is released. Inside the timer, a global counter has been incremented each time the timer runs. The time span of our timer is 1000 milliseconds, that is, one second, but you can get even more control over this process by specifying milliseconds (e.g 100).

There are other possible use cases of this technique, most notably the duration of opening/closing actions of dropdown and flyout menus. You can see an example below.

Example

Live example

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.