Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

foreach function into arrow with addeventlistener

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', () => {
    this.classList.toggle('active'); // `this` refers to `window`
    // Error: Cannot read property 'toggle' of undefined
  });
});
This code will throw an error anytime the matching element is clicked, firing the event listener and executing the callback, due to the window object not having a classList property. Oftentimes, however, the code could fail silently as it might for example check for a condition that always evaluates to false for window while it should evaluate to true for a given element, resulting in many headaches and wasted hours until the issue is discovered and fixed.

To deal with this, one could simply use the first argument of the callback function and Event.target or Event.currentTarget depending on their needs:

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', (e) => {
    e.currentTarget.classList.toggle('active'); // works correctly
  });
});
Comment

foreach function into arrow with addeventlistener

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', function() {
    this.classList.toggle('active');
  });
});
In the example above, we use NodeList.prototype.forEach() to iterate over the nodes matching a given selector and EventTarget.addEventListener() with a regular function as the callback for the 'click' event to swap between an active and inactive state for the clicked element. As we are using a regular function, the this context inside the callback will be bound to the element on which the event was fired.

Arrow functions as callbacks
As we have already explained, arrow functions do not have their own bindings for this. So what happens if we convert the previous code snippet's callback to an arrow function? Its this context refers to the global one, which in this case is the window object.

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', () => {
    this.classList.toggle('active'); // `this` refers to `window`
    // Error: Cannot read property 'toggle' of undefined
  });
});
This code will throw an error anytime the matching element is clicked, firing the event listener and executing the callback, due to the window object not having a classList property. Oftentimes, however, the code could fail silently as it might for example check for a condition that always evaluates to false for window while it should evaluate to true for a given element, resulting in many headaches and wasted hours until the issue is discovered and fixed.

To deal with this, one could simply use the first argument of the callback function and Event.target or Event.currentTarget depending on their needs:

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', (e) => {
    e.currentTarget.classList.toggle('active'); // works correctly
  });
});
Image credit: Matthew Smith on Unsplash
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript 00:00:00 / 00:00:00 clock 
Javascript :: update url parameters and create history entry 
Javascript :: Texto unitário no node js 
Javascript :: express request url ignores hash 
Javascript :: js string encode decode arabic 
Javascript :: Div draggable x axe only 
Javascript :: date and month are swapping in angular 
Javascript :: chrome console print to variable to json 
Javascript :: react native tdd emzyme 
Javascript :: javascript firestore autoID 
Javascript :: mongoose $in operator order not respected 
Javascript :: changing parent function states in child function 
Javascript :: Biliothek 
Javascript :: angular generer guard 
Javascript :: tskill nodejs port 
Javascript :: random order of buttons on refresh in vanilla js 
Javascript :: generators javascript in class 
Javascript :: js browse file 
Javascript :: ex:javascript array 
Javascript :: nsenter 
Javascript :: ui5 React bind element 
Javascript :: $("#symptomSelector").symptomSelector WHAT DOES THIS MEAN IN JAVASCRIPT 
Javascript :: 231105 color 
Javascript :: iframe set value on input outside js 
Javascript :: remove a function added to eventhandler 
Javascript :: isdisplayed method 
Javascript :: how to turn a page upside down in javascript 
Javascript :: get the first value when mapping through the array 
Javascript :: node-lambda run error fs-extralibmkdirsmake-dir.js } catch { Unexpected token 
Javascript :: javascript program german to english translation 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =