Javascript Events and Event Handling
Events and Event Handling in JS:
Events are actions or occurrences that take place within the browser, consisting of a consumer clicking a button, pressing a key, or resizing the window.
Event listeners are utilized on such occasions, and they respond to customers’ engagements.
Basic Concepts:
Events:
A produced event is operation which takes place in the context of browser, and it can be consumer clicking the button or key or even the browser window can be resized by the consumer.
Examples: Such as single and double click a button, submitting a form, pressing a key, changing the window size and so on.
Event Listeners:
Event listeners are functionalities that ‘wait’ for a selected event to happen then executes a predetermined piece of code (callback function).
They are used to handle consumers relations.
Example: Click Event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling Example</title>
</head>
<body>
<button id="myButton">Click me</button>
<script>
// Get the button element
const button = document.getElementById('myButton');
// Add an event listener for the click event
button.addEventListener('click', function() {
alert('Button Clicked!');
});
</script>
</body>
</html>
In this example:
- The HTML report has a button called My button the button id is "myButton".
- In the case of this JavaScript code, the script attaches an occasion listener to the button with addEventListener.
- To the confidential one in the occasion listener, when the button is clicked, an alert shows.
Handling Form Submission:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission Example
</head>
<body>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<button type="submit">Submit</button>
</form>
<script>
// Get the form element
const form = document.getElementById('myForm');
// Add an event listener for the form submission event
form.addEventListener('submit', function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get the input value and display it
const usernameInput = document.getElementById('username');
alert('Submitted: ' + usernameInput.value);
});
</script>
</body>
</html>
- As previously discussed, the HTML document incorporates a shape with an enter field and a put up button.
- This JavaScript script runs an occasion listener on the shape to listen to the submit occasion.
- The nameless characteristic inside the event listener eliminates the normal form submission process when making use of occasion.
Prevents the system from performing the default action, which is a page postback, and displays an alert window with the provided username.