JavaScript events are actions or occurrences that happen in a web page, such as a user clicking a button, a page finishing loading, or a form being submitted. Here are some examples of how to handle events in JavaScript:
- Handle a button click event:
var button = document.getElementById('myButton'); button.addEventListener('click', function() { console.log('Button clicked!'); });
- Handle a page load event:
window.addEventListener('load', function() { console.log('Page loaded!'); });
- Handle a form submission event:
var form = document.getElementById('myForm'); form.addEventListener('submit', function(event) { event.preventDefault(); console.log('Form submitted!'); });
- Handle a mouse over event:
var element = document.getElementById('myElement'); element.addEventListener('mouseover', function() { console.log('Mouse over!'); });
- Handle a key press event:
document.addEventListener('keypress', function(event) { console.log('Key pressed: ' + event.key); });
These are just a few examples of the types of events you can handle in JavaScript. There are many more events available, and you can also create your own custom events using the Event interface.