In this tutorial, we'll explore how to handle events with JavaScript. Events 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. For example, if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box.
By the end of this tutorial, you'll be able to:
Prerequisites: You should have a basic understanding of HTML and JavaScript.
An event in JavaScript represents the precise moment when something happens. Examples of events:
The most common way to listen to events in JavaScript is by using a function called addEventListener()
. It waits for the specified event to occur, then runs a function.
element.addEventListener(event, function, useCapture);
false
.Here's a simple example of a button click event:
<button id="myButton">Click me!</button>
// Select the button element
var btn = document.getElementById('myButton');
// Add a click event listener
btn.addEventListener('click', function() {
alert('Button clicked!');
});
When the button with the ID of myButton
is clicked, an alert box will appear with the text "Button clicked!".
This example shows how to run a function when the web page has finished loading:
// Add a load event listener to the window
window.addEventListener('load', function() {
console.log('Page loaded');
});
When the page has finished loading, "Page loaded" will be logged to the console.
In this tutorial, you've learned how to handle events with JavaScript. You now know how to use the addEventListener()
function to respond to user interactions like clicks and page load events.
Next, you can learn more about the different types of events that can be handled with JavaScript, such as form events, mouse events, and keyboard events. You can also learn more about event propagation, and how to stop it with methods like event.stopPropagation()
and event.preventDefault()
.
Solutions
html
<button id="changeColor">Change Color</button>
javascript
document.getElementById('changeColor').addEventListener('click', function() {
document.body.style.backgroundColor = 'blue';
});
javascript
window.addEventListener('load', function() {
console.log(new Date());
});
html
<input id="myInput" type="text">
javascript
document.getElementById('myInput').addEventListener('input', function(event) {
if (event.target.value === 'JavaScript') {
alert('You entered the keyword!');
}
});
Remember, practice makes perfect. Keep working on different examples to get a good grasp of handling events in JavaScript.