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.