{"id":1109,"date":"2025-07-21T10:00:00","date_gmt":"2025-07-21T10:00:00","guid":{"rendered":"http:\/\/sobre-portugal.com\/?p=1109"},"modified":"2025-07-23T20:24:58","modified_gmt":"2025-07-23T20:24:58","slug":"handling-javascript-event-listeners-with-parameters","status":"publish","type":"post","link":"http:\/\/sobre-portugal.com\/index.php\/2025\/07\/21\/handling-javascript-event-listeners-with-parameters\/","title":{"rendered":"Handling JavaScript Event Listeners With Parameters"},"content":{"rendered":"

Handling JavaScript Event Listeners With Parameters<\/title><\/p>\n<article>\n<header>\n<h1>Handling JavaScript Event Listeners With Parameters<\/h1>\n<address>Amejimaobari Ollornwi<\/address>\n<p> 2025-07-21T10:00:00+00:00<br \/>\n 2025-07-23T20:03:16+00:00<br \/>\n <\/header>\n<p>JavaScript event listeners are very important, as they exist in almost every web application that requires interactivity. As common as they are, it is also essential for them to be managed properly. Improperly managed event listeners can lead to memory leaks and can sometimes cause performance issues in extreme cases.<\/p>\n<p>Here\u2019s the real problem: <strong>JavaScript event listeners are often not removed after they are added.<\/strong> And when they are added, they do not require parameters most of the time — except in rare cases, which makes them a little trickier to handle.<\/p>\n<p>A common scenario where you may need to use parameters with event handlers is when you have a dynamic list of tasks, where each task in the list has a \u201cDelete\u201d button attached to an event handler that uses the task\u2019s ID as a parameter to remove the task. In a situation like this, it is a good idea to remove the event listener once the task has been completed to ensure that the deleted element can be successfully cleaned up, a process known as <a href=\"https:\/\/javascript.info\/garbage-collection\">garbage collecti<\/a><a href=\"https:\/\/javascript.info\/garbage-collection\">on<\/a>.<\/p>\n<h2 id=\"a-common-mistake-when-adding-event-listeners\">A Common Mistake When Adding Event Listeners<\/h2>\n<p>A very common mistake when adding parameters to event handlers is calling the function with its parameters inside the <code>addEventListener()<\/code> method. This is what I mean:<\/p>\n<pre><code class=\"language-javascript\">button.addEventListener('click', myFunction(param1, param2));\n<\/code><\/pre>\n<p>The browser responds to this line by immediately calling the function, irrespective of whether or not the click event has happened. In other words, the function is invoked right away instead of being deferred, so it never fires when the click event actually occurs.<\/p>\n<p>You may also receive the following console error in some cases:<\/p>\n<figure class=\"\n \n break-out article__image\n \n \n \"><\/p>\n<p> <a href=\"https:\/\/files.smashing.media\/articles\/handling-javascript-event-listeners-parameters\/1-uncaught-typeerror.png\"><\/p>\n<p> <img decoding=\"async\" loading=\"lazy\" width=\"800\" height=\"75\" src=\"https:\/\/res.cloudinary.com\/indysigner\/image\/fetch\/f_auto,q_80\/w_400\/https:\/\/files.smashing.media\/articles\/handling-javascript-event-listeners-parameters\/1-uncaught-typeerror.png\" alt=\"Uncaught TypeError\" \/><\/p>\n<p> <\/a><figcaption class=\"op-vertical-bottom\">\n Uncaught TypeError: Failed to execute. <code>addEventListener<\/code> on <code>EventTarget<\/code>: parameter is not of type <code>Object<\/code>. (<a href=\"https:\/\/files.smashing.media\/articles\/handling-javascript-event-listeners-parameters\/1-uncaught-typeerror.png\">Large preview<\/a>)<br \/>\n <\/figcaption><\/figure>\n<p>This error makes sense because the second parameter of the <code>addEventListener<\/code> method <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/EventTarget\/addEventListener#listener\">can only accept<\/a> a JavaScript function, an object with a <code>handleEvent()<\/code> method, or simply <code>null<\/code>. A quick and easy way to avoid this error is by changing the second parameter of the <code>addEventListener<\/code> method to an arrow or anonymous function.<\/p>\n<pre><code class=\"language-javascript\">button.addEventListener('click', (event) => {\n myFunction(event, param1, param2); \/\/ Runs on click\n});\n<\/code><\/pre>\n<p>The only hiccup with using arrow and anonymous functions is that they cannot be removed with the traditional <code>removeEventListener()<\/code> method; you will have to make use of <code>AbortController<\/code>, which may be overkill for simple cases. <code>AbortController<\/code> shines when you have multiple event listeners to remove at once.<\/p>\n<p>For simple cases where you have just one or two event listeners to remove, the <code>removeEventListener()<\/code> method still proves useful. However, in order to make use of it, you\u2019ll need to store your function as a reference to the listener.<\/p>\n<h2 id=\"using-parameters-with-event-handlers\">Using Parameters With Event Handlers<\/h2>\n<p>There are several ways to include parameters with event handlers. However, for the purpose of this demonstration, we are going to constrain our focus to the following two:<\/p>\n<h3 id=\"option-1-arrow-and-anonymous-functions\">Option 1: Arrow And Anonymous Functions<\/h3>\n<p>Using arrow and anonymous functions is the fastest and easiest way to get the job done.<\/p>\n<p>To add an event handler with parameters using arrow and anonymous functions, we\u2019ll first need to call the function we\u2019re going to create inside the arrow function attached to the event listener:<\/p>\n<pre><code class=\"language-javascript\">const button = document.querySelector(\"#myButton\");\n\nbutton.addEventListener(\"click\", (event) => {\n handleClick(event, \"hello\", \"world\");\n});\n<\/code><\/pre>\n<p>After that, we can create the function with parameters:<\/p>\n<pre><code class=\"language-javascript\">function handleClick(event, param1, param2) {\n console.log(param1, param2, event.type, event.target);\n}\n<\/code><\/pre>\n<p>Note that with this method, removing the event listener requires the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/AbortController\"><code>AbortController<\/code><\/a>. To remove the event listener, we create a new <code>AbortController<\/code> object and then retrieve the <code>AbortSignal<\/code> object from it:<\/p>\n<pre><code class=\"language-javascript\">const controller = new AbortController();\nconst { signal } = controller;\n<\/code><\/pre>\n<p>Next, we can pass the <code>signal<\/code> from the <code>controller<\/code> as an option in the <code>removeEventListener()<\/code> method:<\/p>\n<pre><code class=\"language-javascript\">button.addEventListener(\"click\", (event) => {\n handleClick(event, \"hello\", \"world\");\n}, { signal });\n<\/code><\/pre>\n<p>Now we can remove the event listener by calling <code>AbortController.abort()<\/code>:<\/p>\n<pre><code class=\"language-javascript\">controller.abort()\n<\/code><\/pre>\n<h3 id=\"option-2-closures\">Option 2: Closures<\/h3>\n<p>Closures in JavaScript are another feature that can help us with event handlers. Remember the mistake that produced a type error? That mistake can also be corrected with closures. Specifically, with closures, a function can access variables from its outer scope.<\/p>\n<p>In other words, we can access the parameters we need in the event handler from the outer function:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">function createHandler(message, number) {\n \/\/ Event handler\n return function (event) {\n console.log(`${message} ${number} - Clicked element:`, event.target);\n };\n }\n\n const button = document.querySelector(\"#myButton\");\n button.addEventListener(\"click\", createHandler(\"Hello, world!\", 1));\n}\n<\/code><\/pre>\n<\/div>\n<p>This establishes a function that returns another function. The function that is created is then called as the second parameter in the <code>addEventListener()<\/code> method so that the inner function is returned as the event handler. And with the power of closures, the parameters from the outer function will be made available for use in the inner function.<\/p>\n<p>Notice how the <code>event<\/code> object is made available to the inner function. This is because the inner function is what is being attached as the event handler. The event object is passed to the function automatically because it\u2019s the event handler.<\/p>\n<p>To remove the event listener, we can use the <code>AbortController<\/code> like we did before. However, this time, let\u2019s see how we can do that using the <code>removeEventListener()<\/code> method instead.<\/p>\n<p>In order for the <code>removeEventListener<\/code> method to work, a reference to the <code>createHandler<\/code> function needs to be stored and used in the <code>addEventListener<\/code> method:<\/p>\n<div class=\"break-out\">\n<pre><code class=\"language-javascript\">function createHandler(message, number) {\n return function (event) {\n console.log(`${message} ${number} - Clicked element:`, event.target);\n };\n}\nconst handler = createHandler(\"Hello, world!\", 1);\nbutton.addEventListener(\"click\", handler);\n<\/code><\/pre>\n<\/div>\n<p>Now, the event listener can be removed like this:<\/p>\n<pre><code class=\"language-javascript\">button.removeEventListener(\"click\", handler);\n<\/code><\/pre>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>It is good practice to always remove event listeners whenever they are no longer needed to prevent memory leaks. Most times, event handlers do not require parameters; however, in rare cases, they do. Using JavaScript features like closures, <code>AbortController<\/code>, and <code>removeEventListener<\/code>, handling parameters with event handlers is both possible and well-supported.<\/p>\n<div class=\"signature\">\n <img decoding=\"async\" src=\"https:\/\/www.smashingmagazine.com\/images\/logo\/logo--red.png\" alt=\"Smashing Editorial\" width=\"35\" height=\"46\" loading=\"lazy\" \/><br \/>\n <span>(gg, yk)<\/span>\n<\/div>\n<\/article>\n","protected":false},"excerpt":{"rendered":"<p>Handling JavaScript Event Listeners With Parameters Handling JavaScript Event Listeners With Parameters Amejimaobari Ollornwi 2025-07-21T10:00:00+00:00 2025-07-23T20:03:16+00:00 JavaScript event listeners are very important, as they exist in almost every web application<\/p>\n<p class=\"more-link\"><a href=\"http:\/\/sobre-portugal.com\/index.php\/2025\/07\/21\/handling-javascript-event-listeners-with-parameters\/\" class=\"readmore\">Continue reading<svg class=\"icon icon-arrow-right\" aria-hidden=\"true\" role=\"img\"> <use href=\"#icon-arrow-right\" xlink:href=\"#icon-arrow-right\"><\/use> <\/svg><span class=\"screen-reader-text\">Handling JavaScript Event Listeners With Parameters<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-1109","post","type-post","status-publish","format-standard","hentry","category-javascript"],"_links":{"self":[{"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/posts\/1109","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/comments?post=1109"}],"version-history":[{"count":1,"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/posts\/1109\/revisions"}],"predecessor-version":[{"id":1110,"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/posts\/1109\/revisions\/1110"}],"wp:attachment":[{"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/media?parent=1109"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/categories?post=1109"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/sobre-portugal.com\/index.php\/wp-json\/wp\/v2\/tags?post=1109"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}