
JavaScript Events
JavaScript events are actions or occurrences that happen in the browser, such as a user clicking a button, hovering over an element, or the page finishing loading. You can use JavaScript to respond to these events and execute specific code or functions.
Here are some commonly used JavaScript events:
- onClick: Occurs when an element is clicked.
- onDoubleClick: Occurs when an element is double-clicked.
- onMouseOver: Occurs when the mouse pointer is moved over an element.
- onMouseOut: Occurs when the mouse pointer is moved out of an element.
- onSubmit: Occurs when a form is submitted.
- onLoad: Occurs when the page finishes loading.
- onKeyPress: Occurs when a key is pressed on the keyboard.
- onChange: Occurs when the value of an input field or select dropdown is changed.
- onFocus: Occurs when an element gets focus (e.g., when an input field is selected).
- onBlur: Occurs when an element loses focus (e.g., when an input field is deselected).
To use these events, you can add event handlers to your HTML elements or attach event listeners in your JavaScript code. Here’s an example of adding an event handler to a button element:
<button id="myButton">Click me</button>
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
// Code to be executed when the button is clicked
console.log("Button clicked!");
});
In this example, the addEventListener
method is used to attach a click event listener to the button element. When the button is clicked, the provided function is executed, which logs a message to the console.
You can customize the event handling code based on your specific needs and desired actions for each event.