Search code examples
javascriptonclickclicktouchontouchlistener

detecting clicks and touch events with vanilla javascript


Good day all. I would like to get the timestamp of the first click or touch on a page. This page could be loaded in a normal browser, or on a webview, so is better to use a vanilla javascript, without any library.

Is that possible to achieve this? Or I must use some jQuery or something? I only would like to save the Date.now() of the first interaction.


Solution

  • If you only want to listen for the first click you could do something simple like this:

    window.onclick = function() {
        var timeStamp = Date.now();
        console.log(timeStamp);
        //do manipulations, send data to server / anything you want to do
    
        //unbind window.onclick (resetting it to empty function)
        window.onclick = function() {}
    }
    

    You can read more about onclick on MDN
    note that this will unbind every onclick bound to the window object itself as you can only have one listener like this. There is however another method which brings the following advantages over doing this window.onclick = function() { ... } thing:

    1. It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well with other libraries/extensions.
    2. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
    3. It works on any DOM element, not just HTML elements.

    So this basically allows you to for instance add events like this:

    //first event listener
    window.addEventListener('click', function() { console.log('click1'); });
    //second event listener (also a click)
    window.addEventListener('click', function() { console.log('click2'); });
    

    the above example will output the following in the console:

    "click1"
    "click2"
    

    The browser support for addEventListener is quite good to even tho if you need to support older browsers you'll have to tread carefully as there will be different implementations across different browsers.

    For (most) touch devices clicks get converted to touches at a penalty of a 300ms delay to check for double taps, this is not all there but quite consistently implemented overal.

    On MDN there is something about a Touch Web API but if you scroll down there is no real support for it yet, other libraries implement code that uses mouse events that are translated to clicks by devices and use that with some object wrapper to fire off custom touch events, Hammer.js is one of those libraries - this one is probably a bit smarter in the sense of it probably using real touch events if they exist but I've never used Hammer.js before for that matter.