Understanding Events
Events in JavaScript are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. They are central to creating interactive web applications, such as clicking a button, entering text in a form, or moving the mouse over a link.
JavaScript can listen to these events and trigger functions as a response, known as event handlers. Here are some examples of how to work with events:
Adding an Event Listener
An event listener is a procedure in JavaScript that waits for an event to occur, like a click or a keypress. Here is how you can set up an event listener for a button click:
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
Event and Event Handler
An event handler is a function that is triggered by an event. For example, you might want to handle a form submission to validate user input:
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
console.log('Form submitted!');
});
Working with Different Event Types
There are many types of events you can listen to in JavaScript. Here are a few common ones:
click— Triggered by clicking on an element.-
mouseover— Occurs when the mouse pointer is over an element. -
mouseout— Occurs when the mouse pointer leaves an element. keydown— Triggered when a key is pressed down.load— Fired when a resource has loaded.
Using Event Properties
Events have properties that provide additional information about the
event. For instance, the keydown event provides a
property to determine which key was pressed:
window.addEventListener('keydown', function(event) {
console.log('Key pressed: ' + event.key);
});
Understanding and utilizing events effectively can significantly enhance the interactivity and functionality of your web applications.
Try it Yourself
Mouse over and out on the box below:
Press any key:
Test Your Knowledge: JavaScript Events
Which method is used to attach an event handler to a specified element?