Callback Functions for Event
Events on a web page include clicking, hovering, and altering elements. JavaScript responds to these events, making websites interactive. Response code is called event handler or listener.
Different methods can describe events and register handlers. Using HTML attributes like onclick or onmouseover directly on items is an outdated way. Unfortunately, one element can usually have one HTML attribute event handler. Another way is setting event handler properties (e.g., element.onclick = function), however it usually limits you to one handler per event type per object.
Adding Event Listeners
Using event listeners with addEventListener() is more modern and versatile. This method lets you add numerous event listeners to one element for the same event type. JavaScript constantly listens for page events via event listeners.
It takes two steps to add event listeners using addEventListener(): first, choose the element, and then apply the addEventListener(“event”, function) syntax. The event type (a string like “click,” “mouseover,” etc.) is the first argument; it does not have the “on” prefix that was used in previous methods.
Using Callback Functions for Event Handling
When the event happens, the function that should be called is the second argument. This function falls within the callback function category. When you write a callback, you provide it to another method (such as addEventListener()) with the hope that it will be called later when an event or condition is satisfied. This callback is automatically triggered by the browser when the given event occurs.
One argument is usually supplied to the callback function (the event handler) when it is called: an event object. This item has information about the event.
Here is an example:
// It’s good practice to ensure the script runs after the element exists in the DOM.
// A common way is to wrap this in a ‘DOMContentLoaded’ listener or place the script at the end of the <body>.
// 1. Select the element using its ID
const myButton = document.querySelector(‘#myButton’);
// Check if the element was found before adding the listener (good practice)
if (myButton) {
// 2. Add the event listener to the selected element
// The first argument is the event type ‘click’ (without ‘on’)
// The second argument is the callback function (an anonymous function here)
myButton.addEventListener(‘click’, function(event) { // The browser will call this function when clicked, passing the event object
// This code inside the function runs when the button is clicked
// Log a simple message to the console
console.log(‘myButton was clicked!’);
// Log the event object to the console
console.log(‘Event details:’, event);
// Use console.dir(event) for a more detailed, interactive view of the object
}); // The optional third argument (useCapture) defaults to false
} else {
// Log an error if the element was not found
console.error(“Element with ID ‘myButton’ not found!”);
}
/*
// Example HTML structure required for this code:
<!DOCTYPE html>
<html>
<head>
<title>Event Listener with Callback</title>
</head>
<body>
<button id=”myButton”>Click Me</button>
<!– Link your JavaScript file here, or place the script directly –>
<script src=”your_script_file.js”></script>
</body>
</html>
*/
In this code, document.querySelector(‘#myButton’) finds the button element with the ID “myButton”. addEventListener(‘click’, …) attaches the listener, specifying that we are interested in the click event. The function(event) { … } is the anonymous callback function. The browser calls this function when a click occurs, providing the event object, which we then log to the console. This demonstrates the use of addEventListener and a callback function to respond to user interaction.
Common Event Examples
Events in JavaScript are web page occurrences that your code may respond to to make content interactive. Functions known as event handlers or event listeners are triggered when a certain event occurs on a given element. The addEventListener() method has been suggested as a contemporary and adaptable approach to attaching these handlers.
onclick Onclick is activated when an element is clicked. When pressed, buttons often perform this action. Also works on links, pictures, checkboxes, radio buttons, and submit/reset buttons.
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick=”alert(‘Button clicked!’)”>Click Me</button>
</body>
</html>
An alert box appears when the button is clicked.
These two event handlers are often used together to produce rollover effects, which modify the appearance of an element when the mouse pointer passes over it.
- onmouseover: Fires when the mouse pointer touches an element + its children.
- onmouseout: When the mouse cursor leaves an element, including its child, onmouseout fires.
Rollover effects typically change the picture of a button as the mouse lingers over it.
Pre-loading images into the browser’s cache improves efficiency, especially with image rollovers. This prevents delays while rolling over the element. Create JavaScript Image objects and set their src property to pre-load images.
Example (Image Rollover):
<!DOCTYPE html>
<html>
<head>
<title>Rollover Example</title>
<script>
// Pre-load images (assuming ‘image_off.gif’ and ‘image_on.gif’ exist)
if (document.images) { // Check browser support
var imgOff = new Image();
imgOff.src = “image_off.gif”; // Path to the default image
var imgOn = new Image();
imgOn.src = “image_on.gif”; // Path to the rollover image
}
function swapImage(imgElement, newSrc) {
if (document.images) {
imgElement.src = newSrc; // Change the image source
}
}
</script>
</head>
<body>
<img src=”image_off.gif”
onmouseover=”swapImage(this, imgOn.src)”
onmouseout=”swapImage(this, imgOff.src)”
alt=”Hover over me”>
</body>
</html>
Onmouseover executes swapImage to change the image source to ‘on’, and onmouseout sets it back to ‘off’. HTML’s this keyword refers to the picture element. Links may need return true in the onmouseover handler to prevent the browser from overwriting a custom status bar message with the URL. Mouseover and mouseout events bubble up the DOM tree, making them harder to control than mouseenter and mouseleave.
onchange User-changed element values trigger the onchange event handler. By clicking outside the field or pressing Tab, this event triggers for most form elements when the user changes the value and shifts the input focus away from the element. Select boxes trigger immediately when a new option is selected. It usually doesn’t fire for every text field keystroke.
Example:
<!DOCTYPE html>
<html>
<body>
<input type=”text” onchange=”console.log(‘Value changed to: ‘ + this.value)” placeholder=”Type something”>
</body>
</html>
The onchange event logs the new value to the console when typing into the input field and clicking elsewhere.
onblur When an element loses focus, onblur is triggered. This signifies the user clicked or tabbed to the element and then switched to another. Whether the element’s value changes or not, onblur fires.
Example:
<!DOCTYPE html>
<html>
<body>
<input type=”text” onblur=”alert(‘Input field lost focus’)”>
<input type=”text” placeholder=”Click here after typing in the first field”>
</body>
</html>
Clicking the first input field and then the second will trigger the first field’s onblur event and alert. Onblur and onfocus (getting focus) are non-bubbling events. The same element should not have onchange and onblur since they may clash.
These HTML event properties make adding interaction easy, especially for simpler cases. Many developers choose addEventListener() for complex situations or for separating HTML and JavaScript code.