skip to Main Content

Beginner in JavaScript here. I’m building a simple calculator using HTML, CSS and JavaScript.
I’ve realized that if I use this instead of document.querySelector(".add") when adding a style to a button inside of an addEventListener, my code still works.

Would that be correct or should I always stick to the original document.querySelector(".add")?

document.querySelector(".add").addEventListener("click", function () {
  let a = Number(document.querySelector(".num1").value);
  let b = Number(document.querySelector(".num2").value);

  this.classList.add("botaoClicado");
  //the above "this" replaces this excerpt: document.querySelector(".add")

  let soma = a + b;
  console.log(soma);

  document.querySelector(".result").textContent = `RESULTADO: ${soma}`;
});

2

Answers


  1. Using this in an event listener refers to the element that triggered the event.

    Since you’re adding the event listener to the .add element, this inside the callback function refers to that .add element. It’s perfectly fine to do so and in this case would save you some extra querySelector calls.

    Login or Signup to reply.
  2. If you have provided a regular Javascript function, then this will be set to event.currentTarget – which is the element you attached the event listener to.

    However, you need to be careful that if you provide an arrow function expression, arrow functions do not have their own bindings to this. Therefore, you will need to use event.currentTarget instead.

    element.addEventListener('click', function(event) {
      // this === event.currentTarget
    })
    
    element.addEventListener('click', event => {
      // this !== event.currentTarget
    })
    
    

    Also note that due to the way that events bubble or are ‘captured’ (depending on whether you specified useCapture when calling addEventListener), the event can fire when you are interacting with a parent or child of the element you attached the event listener to.

    In some circumstances, you may need to check that event.target === event.currentTarget, in order to not have the contents of your event listener run more often than necessary. event.target means the element that caused the event to fire, which may be different than the element you attached the listener to.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search