Instance
Add a click event for the <button> element. When the user taps the button, the "Hello World" is output on the <p> element of the Id= "demo":
function () { document.getElementById ("Demo"). InnerHTML = "Hello World";});
The AddEventListener () method is used to add an event handle to the specified element.
Tip: Use the RemoveEventListener () method to remove the event handle added by the AddEventListener () method.
Browser support
The number in the table represents the version number of the first browser that supports the method.
Method |
Chrome |
IE |
FireFox |
Safari |
Opera |
AddEventListener () |
1.0 |
9.0 |
1.0 |
1.0 |
7.0 |
Note: Internet Explorer 8 and earlier versions of IE do not support the AddEventListener () method, and Opera 7.0 and opera earlier are not supported. However, for browsers that do not support this function, you can use the attachevent () method to add an event handle (see "More instances" for a cross-browser solution).
Grammar
function, usecapture)
Parameter values
Parameters |
Description |
Event |
Have to. A string that specifies the event name.
Note: do not use the "on" prefix. For example, use "click" instead of "onclick".
tip: All HTML DOM events can be viewed in our full HTML DOM event object reference Manual. |
function |
Have to. Specifies the function to execute when the event is triggered.
When the event object is passed into the function as the first argument. The type of event object depends on the specific event. For example, the "click" Event belongs to the MouseEvent (mouse event) object. |
Usecapture |
Optional. A Boolean value that specifies whether the event is executed during the capture or bubbling phase.
Possible values:
- True-the event handle is executed during the capture phase
- false-false-default. Event handles are executed during the bubbling phase
|
Technical details
DOM version: |
DOM Level 2 Events |
return value: |
No return value |
Recording: |
The usecapture parameter is optional in Firefox 6 and Opera 11.60. (It's always optional in Chrome, IE, and Safari).
|
More instance Instances
You can refer to external functions by function names.
This example demonstrates how to execute a function when the user taps the <button> element:
document.getElementById ("Mybtn"). AddEventListener ("click", myFunction); function myFunction () { document.getElementById ("Demo"). InnerHTML = "Hello World";}
Ext.: http://www.runoob.com/jsref/met-element-addeventlistener.html
HTML DOM AddEventListener () method