Two Quick Steps to JavaScript Events
If you're just starting out with JavaScript and want to respond to an event on the page, you can keep these two simple steps in mind. For this example, we will look at responding to a click event on an anchor tag.
Click here.
Including an id
attribute will allow us to easily find the element within the page.
1. Listen for an event.
We first find the anchor tag, and begin listening for its click event. Listening is accomplished by calling the element's addEventListener
method and providing a callback function.
var anchor = document.getElementById("click-target"); anchor.addEventListener("click", handleClickEvent);
Or we can use the element's onclick
property to specify the event callback function.
var anchor = document.getElementById("click-target"); anchor.onclick = handleClickEvent;
2. Implement a callback function.
An event listener always receives an Event
object that describes the event. For our example, we will receive this object as the first argument in the callback function, and reference it with the variable e
.
function handleClickEvent(e) { // Respond to the click event. alert("Anchor was clicked!"); // The default action when clicking an anchor tag is to // redirect the browser to the URL specified in the // href attribute. If we want to prevent the redirect, // we can use the Event object to prevent the default // behavior. e.preventDefault(); }