SnakeDoc SnakeDoc - 25 days ago 14
HTML Question

Determine if onclick was invoked via javascript

I have an input element which uses the

onclick
event to invoke some javascript function, like so:

<input type="checkbox" name="blah" id="blah" onclick="doSomeFunction();"/>


My issue is this
onclick
event is also invoked by some vendor code elsewhere, like:

$('#blah').click();


I cannot modify the code that executes the
onclick
event of this element unfortunately, but can modify the
doSomeFunction()
function.

Is it possible to determine if the
onclick
event was invoked via javascript, or was an actual click?

Answer Source

If you can pass in the event object you can check for some differences in properties like clientX or clientY and isTrusted.

Note I've never done this before but tested it in Firefox and Chrome

function doSomeFunction(event) {
  console.log(event.isTrusted ? 'Manually clicked' : 'Clicked programatically');
  console.log('ClientX=', event.clientX)
}


$('button').click(function() {
  $('#blah').click()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" name="blah" id="blah" onclick="doSomeFunction(event);" />

<button>
Trigger a click
</button>