The HTML DOM enables JavaScript to respond to HTML events.
JavaScript can be triggered when an event occurs, such as when a user clicks on an HTML element.
To run code when a user clicks on an element, you can add JavaScript to the HTML event attribute.
onclick=JavaScript |
Examples of HTML events include:
In this example, the content of the <h1> element changes when the user clicks on it:
<!DOCTYPE html> <html> <body> <h1 onclick=”this.innerHTML = ‘Ooops!'”>Click on this text!</h1> </body> </html> |
In this example, a function is invoked through the event handler.
<!DOCTYPE html> <html> <body> <h1 onclick=”changeText(this)”>Click on this text!</h1> <script> function changeText(id) { id.innerHTML = “Ooops!”; } </script> </body> </html> |