Search code examples
javascriptjqueryonclicklistenerjquery-click-event

JavaScript / jQuery - Any way to detect click type?


In my code I use jQuery's click() function. Is there any way to detect click type? For example the ability to differentiate between mouse clicks and code driven clicks?


Solution

  • Seems to me e.originalEvent is you need:

    $('button').on('click', function (e){
        if (e.originalEvent === undefined) {
            alert ('triggered by code');
        }else {
            alert ('triggered by mouse');
        }
    });
    

    Or may be you would try sending the extra event data to have a check.

    Another option is to have a check for e.isTrigger like:

    $('button').on('click', function (e) {
        if (e.isTrigger) {
            alert ('triggered by code');
        }else {
            alert ('triggered by mouse');
        }
    });