Зміст курсу
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Introduction to Events and Event Listeners
What Are Events in JavaScript?
JavaScript provides mechanisms to handle these events and execute specific code in response, making your web application interactive and dynamic.
Common Event Types
Explanation of addEventListener() and How to Attach Event Listeners
To respond to events in JavaScript, you attach an event listener to an element. The most common method to do this is with the addEventListener()
function, which listens for specific events and calls a function when the event occurs.
event
: The type of event you want to listen for (e.g.,'click'
,'submit'
);function
: The callback function to execute when the event is triggered;useCapture
(optional): A boolean that indicates whether the event should be captured during the capturing or bubbling phase (default isfalse
, meaning it listens during the bubbling phase).
Click Event Listener
Let's attach a click
event listener to the button. When clicked, it triggers an alert.
index
index
index
The event listener is attached to the #myButton
element, and when the user clicks the button, a message box appears with the text "Button clicked!"
Submit Event Listener
Let's add an event listener for the submit
event, preventing the default form submission behavior to handle the data with JavaScript.
index
index
index
An event listener on the form's submit
event prevents the default submission with event.preventDefault()
, allowing custom JavaScript to handle the data instead. Upon submission, the name entered is retrieved and displayed in a paragraph with the ID displayName
.
Keypress Event
Let's attach a keypress
event listener to the input field. When a key is pressed, it will be shown in the paragraph.
index
index
index
Every time a key is pressed while typing into the input field, the pressed key is logged to the console.
Practical Example: Handling Form Validation on Submit
Let's create a logic for the form validation before the form submission.
index
index
index
The submit
event listener ensures the form does not submit if the required fields are empty. If either the username or password field is empty, the event is prevented from proceeding, and an error message is displayed.
Дякуємо за ваш відгук!