Attach a click event to a <button> element.
This example uses the addEventListener()
method to attach a click event to a button.
<!DOCTYPE html> <html> <body> <button id="myBtn">Test</button> <p id="demo"></p> <script> document.getElementById("myBtn").addEventListener("click", function(){ document.getElementById("demo").innerHTML = "Hello World"; });//from w w w .j a v a 2s .c o m </script> </body> </html>
The addEventListener()
method attaches an event handler to the specified element.
Use the removeEventListener()
method to remove an event handler that has been attached with the addEventListener()
method.
Use the document.addEventListener()
method to attach an event handler to the document.
element.addEventListener(event, function, useCapture);
Parameter Values
Parameter | Optional | Description |
---|---|---|
event | Required. | A String that specifies the name of the event. |
function | Required. | the function to run when the event occurs. When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. |
useCapture | Optional. | whether the event should be executed in the capturing or in the bubbling phase. Possible values: true - The event handler is executed in the capturing phase false- Default. The event handler is executed in the bubbling phase |
Return Value: | No return value |
---|