Detect duration of touch

Any suggestions on how best to detect the duration of the touch of an object/button? I want to initiate some action if a button has received a long press (say > 1 sec or > 3 sec). This will be via touchscreen, not mouse. Is this even easily possible?

Thanks.

I’ve sort of got it half working with this …

	function detectLongPress(hypeDocument, element, event) {
	var start, end, duration;
	
	element.addEventListener("mousedown", function(){
		start = new Date();
		});
	
	element.addEventListener("mouseup", function(){
		end = new Date();
		duration = end - start;
		if(duration > 0 && duration < 500) {
			alert("less than half sec "); }
		if(duration >500 && duration < 1000) {
			alert("between half sec and 1 sec "); }
		if(duration > 3000) {
			alert("more than 3 secs "); 
			element.innerHTML = "BONG"; }
		});

Is this vaguely on the right lines?

I had a snippet of code from a hammer.js project that I was helping someone else out on that works well for this:

press-hammer.hype.zip (12.8 KB)

	// Get a reference to an element
var square = hypeDocument.getElementById('square');

// Create a manager to manager the element
var manager = new Hammer.Manager(square);

// Create a recognizer
var Press = new Hammer.Press({
  time: 1000
});

// Add the recognizer to the manager
manager.add(Press);

// Subscribe to desired event
manager.on('press', function(e) {
  hypeDocument.startTimelineNamed('1secpress', hypeDocument.kDirectionForward, false)
});

It plays a timeline after a press has been detected for 1 second. Hammer.js is great if you want to do other touch-related things down the line: https://hammerjs.github.io/

This looks great, Daniel. I’ve not come across Hammer.js before. I think it will suit me exactly. I’ll experiment with it.

Many thanks.