JavaScript Events:
JavaScript events are actions or occurrences that happen in the browser, triggered by the user or the browser itself. JavaScript code can respond to these events by executing functions or scripts.
Here are some common JavaScript events:
1. Click Event:
- Occurs when an element is clicked.
javascript
document.getElementById("myButton").addEventListener("click", function() {
// Code to execute when the button is clicked
});
2. Mouseover Event:
- Occurs when the mouse pointer is moved over an element.
javascript
document.getElementById("myElement").addEventListener("mouseover", function() {
// Code to execute when the mouse is over the element
});
JavaScript Events |
3. Mouseout Event:
- Occurs when the mouse pointer leaves an element.
javascript
document.getElementById("myElement").addEventListener("mouseout", function() {
// Code to execute when the mouse leaves the element
});
4. Change Event:
- Occurs when the value of an input element changes (e.g., input field or dropdown).
javascript
document.getElementById("myInput").addEventListener("change", function() {
// Code to execute when the input value changes
});
5. Submit Event:
- Occurs when a form is submitted.
javascript
document.getElementById("myForm").addEventListener("submit", function(event) {
// Code to execute when the form is submitted
event.preventDefault(); // Prevents the default form submission behavior
});
6. Keydown, Keyup, Keypress Events:
- Occur when a key on the keyboard is pressed, released, or held down.
javascript
document.addEventListener("keydown", function(event) {
// Code to execute when a key is pressed
});
7. Load Event:
- Occurs when the page and its resources finish loading.
javascript
window.addEventListener("load", function() {
// Code to execute when the page has fully loaded
});
8. Resize Event:
- Occurs when the browser window is resized.
javascript
window.addEventListener("resize", function() {
// Code to execute when the window is resized
});
These are just a few examples of JavaScript events. Events allow you to create interactive and dynamic web pages by responding to user actions or changes in the browser environment. You can attach event listeners to HTML elements and define the JavaScript code that should run when an event occurs.