In this tutorial, we're going to explore the JavaScript event object, an integral part of event handling in JavaScript. This object provides information about the event that occurred, such as the type of event, the element that triggered the event, and other details like mouse position, key pressed, etc.
You will learn:
- What the event object is
- How to use the event object
- How to access different properties of the event object
Prerequisites:
- Basic understanding of JavaScript
- Familiarity with HTML and CSS
- Basic understanding of the Document Object Model (DOM)
Whenever an event occurs, the browser creates an event object with details about the event. This object is then passed as an argument to your event handler function.
Here is a basic example:
// This is your event handler function
function handleClick(event) {
console.log(event);
}
// Add the event listener
document.querySelector('button').addEventListener('click', handleClick);
When you click the button, the browser logs the event object to the console.
Here are some common properties you'll find on the event object:
event
or e
for clarity.event.preventDefault()
to stop the default action of an event from happening.document.querySelector('button').addEventListener('click', function(event) {
console.log('Event type: ', event.type); // Logs: 'Event type: click'
});
document.querySelector('button').addEventListener('click', function(event) {
console.log('Event target: ', event.target); // Logs: 'Event target: [object HTMLButtonElement]'
});
In this tutorial, we've learned about the JavaScript event object and its common properties. We've also seen how to use these properties in real-world examples.
Next Steps:
Additional Resources:
Exercise 1:
Create a page with three buttons. When you click a button, log the type of event and the text of the button that was clicked.
Solution:
Here is one way you could solve this exercise:
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<script>
document.querySelectorAll('button').forEach(function(button) {
button.addEventListener('click', function(event) {
console.log('Event type: ' + event.type);
console.log('Clicked button: ' + event.target.textContent);
});
});
</script>
Exercise 2:
Prevent a form from being submitted when the user clicks the submit button.
Solution:
<form id="myForm">
<input type="text" placeholder="Enter text">
<button type="submit">Submit</button>
</form>
<script>
document.querySelector('#myForm').addEventListener('submit', function(event) {
event.preventDefault();
console.log('Form submission prevented!');
});
</script>
By calling event.preventDefault()
, we stop the form from being submitted. Instead, we just log a message to the console.