|
4 | 4 | | :--- | |
5 | 5 | | [Introduction to Events in JavaScript](#introduction-to-events-in-javascript) | |
6 | 6 | | [Different Ways of Listening to Events](#different-ways-of-listening-to-events) | |
| 7 | +| [Removing Event Listeners](#removing-event-listeners) | |
7 | 8 |
|
8 | 9 | ## [Introduction to Events in JavaScript](https://drive.google.com/uc?export=view&id=1tfi-wZ9BYL2wISnyZ2JCcutRPApHpyCV) |
9 | 10 |
|
@@ -46,41 +47,164 @@ In JavaScript, there are several ways to listen to browser events, depending on |
46 | 47 |
|
47 | 48 | 1. **Using the [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) method** - This is the most common way of listening to events in the browser. It allows you to attach an event listener to a specific DOM element and specify the type of event you want to listen to. Here's an example: |
48 | 49 |
|
49 | | -```javascript |
50 | | -const button = document.querySelector('button'); |
| 50 | + ```javascript |
| 51 | + const button = document.querySelector('button'); |
51 | 52 |
|
52 | | -button.addEventListener('click', () => { |
53 | | - console.log('Button clicked'); |
54 | | -}); |
55 | | -``` |
| 53 | + button.addEventListener('click', () => { |
| 54 | + console.log('Button clicked'); |
| 55 | + }); |
| 56 | + ``` |
56 | 57 |
|
57 | 58 | 2. **Using the `on` property** - Some DOM elements have an on property that can be used to attach an event listener. This method is less common than addEventListener, but it can be useful in certain situations. Here's an example: |
58 | 59 |
|
59 | | -```javascript |
60 | | -const input = document.querySelector('input'); |
| 60 | + ```javascript |
| 61 | + const input = document.querySelector('input'); |
61 | 62 |
|
62 | | -input.onchange = () => { |
63 | | - console.log('Input value changed'); |
64 | | -}; |
65 | | -``` |
| 63 | + input.onchange = () => { |
| 64 | + console.log('Input value changed'); |
| 65 | + }; |
| 66 | + ``` |
66 | 67 |
|
67 | 68 | 3. **Using inline event handlers** - This method involves adding event handlers directly to HTML elements using the `onclick`, `onchange`, or other similar attributes. This method is considered outdated and not recommended, but it is still supported in modern browsers. Here's an example: |
68 | 69 |
|
69 | | -```html |
70 | | -<button onclick="console.log('Button clicked')">Click me</button> |
71 | | -``` |
| 70 | + ```html |
| 71 | + <button onclick="console.log('Button clicked')">Click me</button> |
| 72 | + ``` |
72 | 73 |
|
73 | 74 | 4. **Using the [`event`](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event) object** - When an event is triggered, the browser creates an event object that contains information about the event. You can access this object and use it to perform additional operations or modify the default behavior of the event. Here's an example: |
74 | 75 |
|
75 | | -```javascript |
76 | | -const link = document.querySelector('a'); |
| 76 | + ```javascript |
| 77 | + const link = document.querySelector('a'); |
77 | 78 |
|
78 | | -link.addEventListener('click', (event) => { |
79 | | - event.preventDefault(); |
80 | | - console.log('Link clicked'); |
81 | | -}); |
82 | | -``` |
| 79 | + link.addEventListener('click', (event) => { |
| 80 | + event.preventDefault(); |
| 81 | + console.log('Link clicked'); |
| 82 | + }); |
| 83 | + ``` |
83 | 84 |
|
84 | 85 | In this example, we prevent the default behavior of the `click` event (which is to navigate to the link URL) using the [`preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) method on the `event` object. |
85 | 86 |
|
86 | 87 | Overall, the [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) method is the preferred way of listening to browser events in modern JavaScript, as it provides more flexibility and better separation of concerns. However, the other methods may still be useful in certain situations. |
| 88 | + |
| 89 | +## Removing Event Listeners |
| 90 | + |
| 91 | +The [`removeEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) method is used to remove an event listener that was previously added to a DOM element using the `addEventListener()` method. It takes two arguments: the type of the event to remove (as a string), and the callback function that was used to handle the event. |
| 92 | + |
| 93 | +Here's an example that demonstrates how to use `removeEventListener()` to remove an event listener: |
| 94 | +
|
| 95 | +```javascript |
| 96 | +// Get the button element |
| 97 | +const button = document.querySelector('button'); |
| 98 | +
|
| 99 | +// Define the callback function |
| 100 | +function handleClick() { |
| 101 | + console.log('Button clicked'); |
| 102 | +} |
| 103 | +
|
| 104 | +// Add the event listener |
| 105 | +button.addEventListener('click', handleClick); |
| 106 | +
|
| 107 | +// Remove the event listener after 3 seconds |
| 108 | +setTimeout(() => { |
| 109 | + button.removeEventListener('click', handleClick); |
| 110 | +}, 3000); |
| 111 | +``` |
| 112 | +
|
| 113 | +In this example, we start by getting a reference to a button element on the page using the `document.querySelector()` method. We then define a callback function called `handleClick()` that logs a message to the console when the button is clicked. |
| 114 | +
|
| 115 | +Next, we use the `addEventListener()` method to attach the `handleClick()` function to the button element as a click event listener. |
| 116 | +
|
| 117 | +Finally, we use the `setTimeout()` method to remove the event listener after 3 seconds using the `removeEventListener()` method. This ensures that the event listener will only be active for a limited period of time and will not continue to consume resources unnecessarily. |
| 118 | +
|
| 119 | +Note that the second argument of `removeEventListener()` must be the same function that was used to add the event listener. If you pass a different function, the event listener will not be removed. |
| 120 | +
|
| 121 | +While `removeEventListener()` is a powerful and useful method for removing event listeners from DOM elements, there are a few pitfalls that you should be aware of when using it: |
| 122 | +
|
| 123 | +1. **Event listeners must be added and removed with the same function reference**: As mentioned in the previous example, the `removeEventListener()` method requires the same function reference that was used to add the event listener. If you pass a different function reference, the event listener will not be removed. |
| 124 | +
|
| 125 | +2. **Event listeners should not be anonymous functions**: When you add an event listener to a DOM element using an anonymous function, there is no easy way to remove the listener later. This is because you cannot reference an anonymous function by name. To remove an anonymous function event listener, you must use a named function or a reference to the function. |
| 126 | +
|
| 127 | + ```javascript |
| 128 | + const button = document.querySelector('button'); |
| 129 | +
|
| 130 | + // Adding anonymous function event listener |
| 131 | + button.addEventListener('click', function() { |
| 132 | + console.log('Button clicked'); |
| 133 | + }); |
| 134 | +
|
| 135 | + // Attempting to remove the event listener - won't work! |
| 136 | + button.removeEventListener('click', function() { |
| 137 | + console.log('Button clicked'); |
| 138 | + }); |
| 139 | + ``` |
| 140 | + In this example, an anonymous function is used to add an event listener to a button element. However, because the function is anonymous, it cannot be removed later using the `removeEventListener()` method. Therefore, the call to `button.removeEventListener()` has no effect. To avoid this pitfall, you should use named functions to add and remove event listeners, like this: |
| 141 | +
|
| 142 | + ```javascript |
| 143 | + const button = document.querySelector('button'); |
| 144 | + |
| 145 | + // Adding named function event listener |
| 146 | + function handleClick() { |
| 147 | + console.log('Button clicked'); |
| 148 | + } |
| 149 | + button.addEventListener('click', handleClick); |
| 150 | + |
| 151 | + // Removing named function event listener |
| 152 | + button.removeEventListener('click', handleClick); |
| 153 | + ``` |
| 154 | +
|
| 155 | +3. **Removing an event listener that wasn't added**: |
| 156 | +
|
| 157 | + ```javascript |
| 158 | + const button = document.querySelector('button'); |
| 159 | + |
| 160 | + // Adding event listener |
| 161 | + function handleClick() { |
| 162 | + console.log('Button clicked'); |
| 163 | + } |
| 164 | + button.addEventListener('click', handleClick); |
| 165 | + |
| 166 | + // Removing the event listener using a different function reference - won't work! |
| 167 | + function handleOtherClick() { |
| 168 | + console.log('Other click event'); |
| 169 | + } |
| 170 | + button.removeEventListener('click', handleOtherClick); |
| 171 | + ``` |
| 172 | +
|
| 173 | + In this example, a different function reference is used to attempt to remove an event listener that was added earlier. Because the function reference is different, the call to `button.removeEventListener()` has no effect. |
| 174 | +
|
| 175 | + To avoid this pitfall, you should ensure that you are using the same function reference to add and remove event listeners. |
| 176 | +
|
| 177 | +4. **Removing event listeners can impact performance**: While removing event listeners can be a useful way to optimize your code, it can also impact performance if you do it too frequently. Removing and re-adding event listeners repeatedly can cause unnecessary memory allocation and deallocation, which can slow down your application. Therefore, it's important to only remove event listeners when they are no longer needed. |
| 178 | +
|
| 179 | + ```javascript |
| 180 | + const button = document.querySelector('button'); |
| 181 | + |
| 182 | + function handleClick() { |
| 183 | + console.log('Button clicked'); |
| 184 | + } |
| 185 | + |
| 186 | + // Adding event listener |
| 187 | + button.addEventListener('click', handleClick); |
| 188 | + |
| 189 | + // Removing event listener after a delay |
| 190 | + setTimeout(() => { |
| 191 | + button.removeEventListener('click', handleClick); |
| 192 | + }, 1000); |
| 193 | + |
| 194 | + // Re-adding event listener after a delay |
| 195 | + setTimeout(() => { |
| 196 | + button.addEventListener('click', handleClick); |
| 197 | + }, 2000); |
| 198 | + ``` |
| 199 | +
|
| 200 | + In this example, the event listener is removed and then re-added after a delay. However, this is not an efficient way to handle events because it requires unnecessary memory allocation and deallocation. Instead, you should only remove event listeners when they are no longer needed. |
| 201 | +
|
| 202 | + To avoid this pitfall, you should be mindful of how often you are adding and removing event listeners and ensure that you only remove them when they are no longer needed. |
| 203 | +
|
| 204 | +Readings: |
| 205 | +
|
| 206 | +- [Remove an Event Handler](https://www.javascripttutorial.net/dom/events/remove-an-event-handler/) |
| 207 | +
|
| 208 | +- [You’ve Got Options for Removing Event Listeners](https://www.macarthur.me/posts/options-for-removing-event-listeners) |
| 209 | +
|
| 210 | +- [How to remove an event Listener in JavaScript? ](https://linuxhint.com/remove-event-listener-javascript/) |
0 commit comments