0
const buttons = document.querySelectorAll(".btn");
buttons.forEach((btn) => {
  btn.addEventListener("click", (e) => {
    const btnHref = btn.getAttribute('href'); <==== works fine
    const btnHref = this.getAttribute('href'); <==== does not work
    const section = document.querySelector(btnHref);
    const { left, top } = section.getBoundingClientRect();

    window.scrollTo({
      left: left + window.scrollX,
      top: top + window.scrollY,
      behavior: "smooth",
    });
    
    e.preventDefault();
  });
});

I thought that whenever we use addEventListener and inside of a callback the 'this' keyword will be = to the HTML element but in my case, it doesn't work, can someone tell me why? I also had a similar problem in jquery, when some people used the "this" keyword well, I just couldn't since it didn't work.

Rostyk
  • 939
  • 3
  • 13
  • 32
  • 1
    Remove the arrow function and add `function(e)` to your function. Also you're passing the event into it, why not just use `e.target`? Lastly you are also using the defined `btn` variable passed into the `forEach` loop, this also works fine as it is going to get that instance of the iteration. – dale landry Jul 04 '21 at 18:19
  • In Arrow Function the `this` key word acts differently look here https://www.w3schools.com/js/js_arrow_function.asp – Ben.S Jul 04 '21 at 18:36

2 Answers2

0

In arrow function it shoul work if you write: e.target.getAttribute('href');

Luckyfella
  • 557
  • 4
  • 14
0

Use the normal function keyword rather than arrow function.

  btn.addEventListener("click", function (e){
     // this...
  });