javascript events
Javascript Events
Javascript events are actions that occur on a web page, triggered by the user or the browser. They can be used to add interactivity to a website, such as changing the color of a button when it is clicked or displaying a message when the mouse hovers over a certain element.
Types of Events
- Mouse Events: These events are triggered by actions of the mouse, such as clicking, hovering, and dragging.
- Keyboard Events: These events are triggered by typing on the keyboard, such as pressing a key or releasing a key.
- Form Events: These events are triggered by actions on a form, such as submitting the form or resetting the form.
- Document Events: These events are triggered by changes in the document, such as loading the page or resizing the window.
- Window Events: These events are triggered by changes in the window, such as scrolling or closing the window.
Event Handlers
In order to add interactivity to a web page using Javascript events, we use event handlers. An event handler is a function that is called when an event occurs. In order to add an event handler to an element, we use the on[event] property.
//Example of adding an event handler to a button element
const myButton = document.querySelector('#myButton');
myButton.onclick = function() {
alert('Button clicked!');
};
In the above example, we add an onclick event handler to a button element with the id "myButton". When the button is clicked, the function inside the event handler is executed and an alert message is displayed.
Adding Multiple Event Handlers
We can add multiple event handlers to an element by using the addEventListener method. This method takes two arguments, the type of event and the function to be executed when the event occurs.
//Example of adding multiple event handlers to a button element
const myButton = document.querySelector('#myButton');
myButton.addEventListener('click', function() {
alert('Button clicked!');
});
myButton.addEventListener('mouseover', function() {
myButton.style.backgroundColor = 'red';
});
myButton.addEventListener('mouseout', function() {
myButton.style.backgroundColor = 'white';
});
In the above example, we add three event handlers to a button element with the id "myButton". The first event handler displays an alert message when the button is clicked. The second event handler changes the background color of the button when the mouse hovers over it. The third event handler changes the background color back to white when the mouse leaves the button.
Conclusion
Javascript events are a powerful tool for adding interactivity to a website. By using event handlers, we can execute code when certain actions occur on a web page. There are many types of events, and we can add multiple event handlers to an element to create complex interactions.