简体   繁体   中英

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?

When it is clicked physically by mouse, the event has these properties:

clientX: 
clientY: 

So, if they are undefined , it is programmatic.

 $(function () { $("#btn").click(function (e) { console.log(typeof e.clientX); if (typeof e.clientX == "number") alert("Mouse Click"); else alert("Programmatic"); }); $("#pxy").click(function (e) { $("#btn").click(); }); }); 
 * {font-family: 'Segoe UI'; font-size: 10pt;} 
 <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <input type="button" value="Click" id="btn" /> <input type="button" value="Click the Button" id="pxy" /> 

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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM