JS Events 🎯

beginner
14 min

JS Events 🎯

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of JavaScript Events. We'll explore how to make your JavaScript code interactive, respond to user actions, and create dynamic, engaging websites. Let's get started! 🚀

Understanding Events 📝

Events in JavaScript are actions that occur within the browser, such as clicking a button, scrolling a page, or loading a webpage. When an event happens, JavaScript allows us to react to it and run code accordingly.

Types of JavaScript Events 💡

  1. DOM Events: These events are related to the Document Object Model (DOM) and include actions like clicking a button, hovering over an element, or resizing the browser window.

  2. Keyboard Events: These events are triggered when a user interacts with the keyboard, like pressing a key or using the arrow keys.

  3. Mouse Events: These events are triggered by mouse actions, such as clicking, double-clicking, or moving the cursor over an element.

Listening to Events 🎧

To react to an event, we first need to listen for it. This is done by using the addEventListener method.

javascript
// Select the button element const button = document.querySelector('button'); // Listen for the 'click' event on the button button.addEventListener('click', function() { console.log('Button clicked!'); });

In the code above, we're selecting a button element and adding an event listener for the click event. When the button is clicked, the message "Button clicked!" will be logged to the console.

Creating Interactive Buttons 💡

Let's create a simple, interactive button that changes its text when clicked.

javascript
// Initialize the button text let buttonText = 'Click me!'; // Select the button element const button = document.querySelector('button'); // Listen for the 'click' event on the button button.addEventListener('click', function() { // Change the button text button.textContent = 'You clicked me!'; });

In this example, we're initially setting the button text to "Click me!". When the button is clicked, the text changes to "You clicked me!".

Quiz Time 💡

Quick Quiz
Question 1 of 1

Which method is used to listen for events in JavaScript?

Wrapping Up 📝

In this lesson, we learned about JavaScript events, their types, and how to listen for them. We created interactive buttons and gained a solid foundation for making our websites more dynamic and user-friendly.

In the next lesson, we'll dive deeper into DOM manipulation, exploring how to dynamically change HTML elements using JavaScript. Stay tuned! 🌟

Happy coding, and see you soon at CodeYourCraft! 💻💖