In JavaScript, Events are actions or occurrences that happen in the browser, such as user interactions (clicks, mouse movements, keyboard inputs) or changes in the document (loading, resizing).
Handling events is a crucial aspect of building interactive and dynamic web applications.
Here are some commonly used methods and properties related to events:
The `addEventListener` method is used to attach an event handler to an element.
It allows us to specify the type of event to listen for and the function to be called when the event occurs.
const button = document.getElementById('yourButton'); function handleOnClick() { alert('Button click event!'); } button.addEventListener('click', handleOnClick);
The `removeEventListener` method is used to remove an event listener that was previously added.
const button = document.getElementById('yourButton'); function handleOnClick() { alert('Button click event!'); } button.removeEventListener('click', handleOnClick);
It requires the same arguments (event type and callback function) as `addEventListener`.
function handleKeyPress(event) { console.log('Key pressed:', event.key); }
When an event occurs, an event object is automatically created and passed to the event handler.
It contains information about the event, such as the type, target element, and additional properties.
function handleMouseOver(event) { console.log('Mouse over event:', event.type); }
Different types of events (e.g., click, mouseover, keyup) have their corresponding properties and behaviours.
function handleFormSubmit(event) { event.preventDefault(); // Additional handling logic }
We can use the type property of the event object to determine the type of event.
function handleFormSubmit(event) { event.stopPropagation(); // Additional handling logic }
The preventDefault method of the event object can be used to prevent the default action associated with the event (e.g., preventing a form submission).
The stopPropagation method of the event object prevents the event from bubbling up the DOM tree, ensuring that only the intended event handlers are executed when an event occurs. we can stop the default behaviour of the browser using the `stopPropagation()` method.