Every HTML element has a set of attributes that allow for the execution of JavaScript when certain events happen. These attributes are called event attributes and are the name of the event prefixed by "on". For example, to execute JavaScript when a user clicks on the element, put the JavaScript in the onclick
attribute.
In the JavaScript code executed in response to the event, this
is bound to the HTML element and the Event
object can be reached using the event
variable in the scope of the attribute.
Warning: These attributes should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the Window
object, polluting the global namespace.
While these attributes can at times be attractively easy to use, you should avoid using them. Instead, use the EventTarget.addEventListener()
function to add a listener for the event.
Event attributes can be blocked by using Content Security Policy which if used, blocks all inline scripts unless the 'unsafe-inline' keyword is used.
Example using event attributes
This example appends text to an element each time time the <div>
is clicked.
Note: This is an example of how not to do things, using one of these attributes.
<!doctype html> <html> <head> <title>Event Attribute Example</title> <script> function doSomething() { document.getElementById("thanks").innerHTML += "<p>Thanks for clicking!</p>"; } </script> </head> <body> <div onclick="doSomething();">Click me!</div> <div id="thanks"></div> </body> </html>
Try this example below:
Example using event listeners
Instead, you should use EventTarget.addEventListener()
, as shown here:
<!doctype html> <html> <head> <title>Event Attribute Example</title> <script> function doSomething() { document.getElementById("thanks").innerHTML += "<p>Thanks for clicking!</p>"; } // Called when the page is done loading; this is where we do any setup we need, // such as creating event listeners for the elements in the page. function setup() { document.getElementById("click").addEventListener("click", doSomething, true); } // Install an event handler on the window to receive the "load" event, which // indicates that the document has finished loading into the window. window.addEventListener("load", setup, true); </script> </head> <body> <div id="click">Click me!</div> <div id="thanks"></div> </body> </html>
You can see this in action below: