JavaScript adds interactivity to web pages. This article shows you how to trigger JavaScript functions when an HTML element is clicked using onclick() events and attributes. Code examples included.
JavaScript Events
An event in JavaScript simply means that something has happened. The mouse has moved, or a key has been pressed, and JavaScript has been notified by the raising of an event.
onclick Event
When the user clicks on something, the onclick event is raised, allowing you to trigger some JavaScript code when an element is clicked.
Defining onclick Events
There are several ways to define onclick events, outlined below.
Inline HTML
The first method is to simply place the JavaScript code in an onclick attribute inside the HTML tag for the element you wish to make clickable:
<element onclick="myFunction">
Note that:
- element is any HTML element, usually a <button> or an <a> link
- myFunction is the JavaScript code you want to execute when the element is clicked
Example
<a href="#" onclick="alert("You clicked me!");">Click me!</a>
Above, an HTML link is defined. Usually, the href attribute points to the address of another website or page, but in this case, it’s set to # – meaning it leads nowhere.
An onclick attribute has been added, which pops up a JavaScript alert.
When the link is clicked, the onclick event is fired, and the alert is shown.
Event Handlers
Keeping your JavaScript code separated from your HTML code makes your code more manageable overall – you don’t have to go hunting through the HTML when debugging or updating your JavaScript logic. The following methods separate the onclick event handlers entirely:
object.onclick = function(){myFunction};
Note that:
- object is a reference to the HTML element you wish to make clickable
- myFunction is the code you wish to execute when it is clicked
Example
<button id="clickable">Click me!</button> <script> document.getElementById("clickable").onclick = function() {alert("You clicked me!");}; </script>
As you can see, all of the JavaScript is now in the same place, so you can see exactly what’s going on. The HTML portion only contains the element to be displayed to the user – the logic is separated.
Event Listeners
Event listeners can be used to serve the same purpose as above – separating the JavaScript Logic from the HTML layout.
object.addEventListener("click", myFunction);
Example
<button id="clickable">Click me!</button> <script> document.getElementById("clickable").addEventListener("click", alert("You clicked me!")); </script>
One common use for onclick() is to refresh the page in a web browser.