What are the different types of events in JavaScript?
In JavaScript, events are actions or occurrences that happen in the browser or web page, such as a user clicking a button or a page finishing loading. There are many types of events in JavaScript, but they can be broadly categorized into three categories:
User Interface (UI) events: These events are triggered by user actions, such as clicking a button, typing into a form field, or scrolling a page. Examples include:
click
mouseover
mouseout
keydown
keyup
focus
blur
Network events: These events are triggered by changes in network connectivity, such as a page finishing loading, an AJAX request completing, or a WebSocket connection closing. Examples include:
load
unload
beforeunload
error
online
offline
Browser events: These events are triggered by changes in the browser state, such as the page being resized or the back button being clicked. Examples include:
resize
scroll
popstate
In addition to these three categories, there are also custom events that can be created by JavaScript code using the CustomEvent constructor.
Event handling in JavaScript typically involves attaching event listeners to elements using the addEventListener method, which takes the name of the event and a callback function that will be called when the event is triggered. For example:
var button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
console.log('Button clicked!');
});