Event Keyword In Js
Solution 1:
The Event
object is automatically passed to all event handlers. If you add event handlers with addEventListener
, you can choose the parameter name (like you did in handler
). But for code attached with the onclick
attribute, you can only access the event object via the implicit variable event
.
If you want to know more about event handling in general, I suggest to read about it at quirksmode.org.
Also have a look at MDC - Event handlers:
These are properties that correspond to the HTML 'on' event attributes.
Unlike the corresponding attributes, the values of these properties are functions (or any other object implementing the EventListener interface) rather than a string. In fact, assigning an event attribute in HTML creates a wrapper function around the specified code. For example, given the following HTML:
<divonclick="foo();">click me!</div>
If
element
is a reference to thisdiv
, the value ofelement.onclick
is effectively:
function onclick(event) { foo(); }
Note how the event object is passed as parameter
event
to this wrapper function.
Solution 2:
When an event attribute is set, an implicit Function is created with event
as the first argument. When the event fires, the event object is passed to that function. There wasn't a solid definition on this behavior until HTML 5 (which is still a draft), but it's been this way for a long time in the major browsers and that's how it made it into the spec:
When an event handler's Function object is invoked, its
call()
callback must be invoked with one argument, set to theEvent
object of the event in question.
That argument is aptly named event
for obvious reasons. http://www.w3.org/TR/html5/webappapis.html#events
Solution 3:
This really threw me. The following 'typo' works in Chromium, but not FF:
some_worker.onmessage = function(e) {
// do stuffif (e.datainstanceofArrayBuffer)
intArray = newUint8Array(event.data);
// do other stuff
};
Chromium was observing the implicit keyword for 'event' but FF threw an 'undefined variable' error! Just changed 'event' to 'e' and all is well.
I notice that even stackoverflow's code markup observes 'event' as an implicit keyword ... not to knock FF, since it detected the typo.
Solution 4:
I guess your are trying to pass the clicked HTML element to your handler()
function. The correct way to do that i your code is:
<h1 onclick="handler(this);">Click on this text</h1>
However I strongly recommend avoid this approach. Avoid having styling and behavior defined on the HTML. Please read the following article: Unobtrusive JavaScript
Post a Comment for "Event Keyword In Js"