Event manipulation is primarily done using the concept of event handlers in JavaScript. You can manipulate events through a series of steps:
1. Selecting an HTML element: Before you can manipulate an event, you’ll need to choose the specific HTML element that the event will be associated with. This is done using various methods such as `getElementById()`, `getElementsByClassName()`, `getElementsByTagName()`, or `querySelector()` etc. Example:
\`\`\`javascript var button = document.getElementById(‘myButton’); \`\`\`1. Creating the Event Handler: Event handlers are functions that will be run when a specific event is triggered. This function will contain all the behavior you want the event to carry out. Example:
\`\`\`javascript function buttonClick() { alert(‘Button clicked!’); } \`\`\`1. Assigning the Event Handler to an Event of an Element: The event handler function is then assigned to a specific event of an HTML element. Some common events include `onclick`, `onload`, `onmouseover`, etc. Example:
\`\`\`javascript button.onclick = buttonClick; \`\`\` This statement means that when the ‘click’ event is triggered on the button, it should execute the `buttonClick()` function.In modern (and more complex) JavaScript you might see event listeners used instead of directly assigning an event handler. Here’s how you use the `addEventListener()` method:
```
button.addEventListener(‘click’, function() {
alert(‘Button clicked!’);
});
```
Listeners are a more advanced way of handling events that provide more flexibility and capabilities.
With `addEventListener()`, you can:
- Add multiple separate functions to the same event
- Remove a specific function from being an event handler
- Stop an event from bubbling up the HTML structure
- Prevent default behavior of HTML elements
There are many different types of events that you can listen to and handle in different ways, providing a great deal of interactivity in your site or application.