Handling Events
In web development, events are user actions or interactions with the web page, such as clicking a button, hovering over an element, or submitting a form. JavaScript allows us to handle these events and perform specific actions in response.
To handle events in JavaScript, we can use the addEventListener()
method. This method takes two arguments: the type of the event to listen for, and a callback function to be executed when the event occurs.
Here's an example of adding event listeners to two HTML elements, button
and input
, using JavaScript:
1const button = document.getElementById('myButton');
2const input = document.getElementById('myInput');
3
4button.addEventListener('click', () => {
5 console.log('Button clicked!');
6});
7
8input.addEventListener('change', () => {
9 console.log('Input changed!');
10});
In this example, we select the button
and input
elements using methods like getElementById
and assign them to variables. Then, we use the addEventListener()
method to attach event handlers to these elements. When the button is clicked, the callback function is executed and logs 'Button clicked!' to the console. When the input value changes, the callback function is executed and logs 'Input changed!' to the console.
Try adding event listeners to different elements in your own web page using JavaScript. You can use different types of events such as click
, mouseover
, keydown
, or submit
, and perform different actions based on the event.
Remember, handling events allows us to create interactive web pages and provide a better user experience for our website visitors.
xxxxxxxxxx
const button = document.getElementById('myButton');
const input = document.getElementById('myInput');
button.addEventListener('click', () => {
console.log('Button clicked!');
});
input.addEventListener('change', () => {
console.log('Input changed!');
});