Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
DOM event
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Event handling models == === DOM Level 0 === This event handling model was introduced by [[Netscape Navigator]], and remains the most cross-browser model {{As of|2005|lc=on}}.{{Citation needed|date=September 2012}} There are two model types: the inline model and the traditional model. ==== Inline model ==== In the inline model,<ref>{{cite web |url= http://www.quirksmode.org/js/events_early.html |title= Early event handlers |publisher= Quirksmode.org |access-date= 15 September 2012 }}</ref> event handlers are added as attributes of elements. In the example below, an [[alert dialog box]] with the message "Hey Joe" appears after the [[hyperlink]] is clicked. The default click action is cancelled by returning false in the event handler. <syntaxhighlight lang="html"> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Inline Event Handling</title> </head> <body> <h1>Inline Event Handling</h1> <p>Hey <a href="http://www.example.com" onclick="triggerAlert('Joe'); return false;">Joe</a>!</p> <script> function triggerAlert(name) { window.alert("Hey " + name); } </script> </body> </html> </syntaxhighlight> One common misconception{{Citation needed|date=September 2012}} with the inline model is the belief that it allows the registration of event handlers with custom arguments, e.g. <code>name</code> in the <code>triggerAlert</code> function. While it may seem like that is the case in the example above, what is really happening is that the [[JavaScript engine]] of the browser creates an [[anonymous function]] containing the statements in the <code>onclick</code> attribute. The <code>onclick</code> handler of the element would be bound to the following anonymous function: <syntaxhighlight lang="javascript"> function () { triggerAlert('Joe'); return false; } </syntaxhighlight> This limitation of the JavaScript event model is usually overcome by assigning attributes to the function object of the event handler or by using [[Closure (computer science)|closures]]. ==== Traditional model ==== In the traditional model,<ref>{{cite web |url= http://www.quirksmode.org/js/events_tradmod.html |title= Traditional event registration model |publisher= Quirksmode.org |access-date= 15 September 2012 }}</ref> event handlers can be added or removed by scripts. Like the inline model, each event can only have one event handler registered. The event is added by assigning the handler name to the event property of the element object. To remove an event handler, simply set the property to null: <syntaxhighlight lang="html"> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Traditional Event Handling</title> </head> <body> <h1>Traditional Event Handling</h1> <p>Hey Joe!</p> <script> var triggerAlert = function () { window.alert("Hey Joe"); }; // Assign an event handler document.onclick = triggerAlert; // Assign another event handler window.onload = triggerAlert; // Remove the event handler that was just assigned window.onload = null; </script> </body> </html> </syntaxhighlight> To add parameters: <syntaxhighlight lang="javascript"> var name = 'Joe'; document.onclick = (function (name) { return function () { alert('Hey ' + name + '!'); }; }(name)); </syntaxhighlight> Inner functions preserve their [[Scope (programming)|scope]]. === DOM Level 2 === The W3C designed a more flexible event handling model in DOM Level 2.<ref name="dom2-events"/> {| class="wikitable" ! Name ! Description ! Argument type ! Argument name |- | rowspan=3 | addEventListener | rowspan=3 | Allows the registration of event listeners on the event target. | DOMString | type |- | EventListener | listener |- | boolean | useCapture |- | rowspan=3 | removeEventListener | rowspan=3 | Allows the removal of event listeners from the event target. | DOMString | type |- | EventListener | listener |- | boolean | useCapture |- | dispatchEvent | Allows sending the event to the subscribed event listeners. | Event | evt |- |} Some useful things to know : * To prevent an event from bubbling, developers must call the <code>stopPropagation()</code> method of the event object. * To prevent the default action of the event to be called, developers must call the <code>preventDefault()</code> method of the event object. The main difference from the traditional model is that multiple event handlers can be registered for the same event. The <code>useCapture</code> option can also be used to specify that the handler should be called in the capture phase instead of the bubbling phase. This model is supported by [[Mozilla]], [[Opera browser|Opera]], [[Safari (web browser)|Safari]], [[Google Chrome|Chrome]] and [[Konqueror]]. ==== A rewrite of the example used in the traditional model ==== <syntaxhighlight lang="html"> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>DOM Level 2</title> </head> <body> <h1>DOM Level 2</h1> <p>Hey Joe!</p> <script> var heyJoe = function () { window.alert("Hey Joe!"); } // Add an event handler document.addEventListener( "click", heyJoe, true ); // capture phase // Add another event handler window.addEventListener( "load", heyJoe, false ); // bubbling phase // Remove the event handler just added window.removeEventListener( "load", heyJoe, false ); </script> </body> </html> </syntaxhighlight> === Internet Explorer-specific model === Microsoft Internet Explorer prior to version 8 does not follow the W3C model, as its own model was created prior to the ratification of the W3C standard. Internet Explorer 9 follows DOM level 3 events,<ref>{{cite web|url=http://blogs.msdn.com/ie/archive/2010/03/26/dom-level-3-events-support-in-ie9.aspx|title=DOM Level 3 Events support in IE9|access-date=2010-03-28|publisher=[[Microsoft]]|date=March 26, 2010}}</ref> and Internet Explorer 11 deletes its support for Microsoft-specific model.<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx|title=Compatibility changes in IE11 Preview|access-date=2013-10-05|publisher=[[Microsoft]]|date=September 9, 2013}}</ref> {| class="wikitable" ! Name ! Description ! Argument type ! Argument name |- | rowspan=2 | attachEvent | rowspan=2 | Similar to W3C's addEventListener method. | String | sEvent |- | Pointer | fpNotify |- | rowspan=2 | detachEvent | rowspan=2 | Similar to W3C's removeEventListener method. | String | sEvent |- | Pointer | fpNotify |- |- | rowspan=2 | fireEvent | rowspan=2 | Similar to W3C's dispatchEvent method. | String | sEvent |- | Event | oEventObject |- |} Some useful things to know : * To prevent an event bubbling, developers must set the event's <code>cancelBubble</code> property. * To prevent the default action of the event to be called, developers must set the event's <code>returnValue</code> property. * The '''<code>this</code>''' keyword refers to the global '''<code>window</code>''' object. Again, this model differs from the traditional model in that multiple event handlers can be registered for the same event. However the <code>useCapture</code> option can not be used to specify that the handler should be called in the capture phase. This model is supported by Microsoft [[Internet Explorer]] and [[List of web browsers#Trident-based browsers|Trident based browsers]] (e.g. [[Maxthon]], Avant Browser). ==== A rewrite of the example used in the old Internet Explorer-specific model ==== <syntaxhighlight lang="html"> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Internet Explorer-specific model</title> </head> <body> <h1>Internet Explorer-specific model</h1> <p>Hey Joe!</p> <script> var heyJoe = function () { window.alert("Hey Joe!"); } // Add an event handler document.attachEvent("onclick", heyJoe); // Add another event handler window.attachEvent("onload", heyJoe); // Remove the event handler just added window.detachEvent("onload", heyJoe); </script> </body> </html> </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)