In general, avoid using onxyz
-attribute-style event handlers. But if you do, call them setting this
correctly and passing in the event; you may also want to include return
if you want to use return false
in the handler to prevent the default action of the event:
<button onclick = "return eventHandler.call(this, event)">Test</button>
<!-- --------------^^^^^^--------------^^^^^^^^^^^^^^^^^ -->
(Without the return, on modern browsers, you can use the preventDefault()
method on the event object instead of returning false.)
Within the handler, this
will refer to the element (the button
, in this case) and the first argument will be the event object, which has other useful information.
Note that this handler does not handle the submit
event. It handles a click
event on a submit button. submit
is an event fired at forms, not buttons.
But, in general I'd recommend modern event handling, which hooks up the event once the button exists:
var btn = document.querySelector("selector-for-the-button");
btn.addEventListener("click", eventHandler, false);
With that, eventHandler
will be called with the correct this
and passed the event object.
Note: The obsolete browsers IE8 and earlier do not have addEventListener
. The obsolete browsers IE9-IE10 have it but pretend they don't when they're in "compatibility" mode. IE11 similarly hobbles itself when in "compatibility" mode. If you need to support any of those, you can use the hookEvent
function in this answer.
Or of course, use a library like jQuery, or a framework like AngularJS or React, etc., that handles those cross-browser issues for you.