Why when I use the arrow function with (onclick.) as in the picture,It sends an error in console ??!
Hello @albaraa_1949
could you share the code ?
HTML :
<button> Click Here</button>
JS
const btn = document.querySelector("button");
btn.onclick = () => {
this.classList.toggle("clicked");
};
cause this
does not mean the btn
use this instead
btn.onclick = (e) => {
e.target.classList.toggle("clicked");
};
e is the event that sent when the button get clicked then we get the target of the event then do whatever we like with it
Edit : try to use an ide it will help you a lot with those type of error and even give you list of methods for each object/variable
But when I use the anonymous function the error message does not appear, as in the exampl
btn.onclick = function () {
this.classList.toggle("clicked");
};
I also didn’t quite understand how to apply what you told me in this paragraph:
Could you explain that please?
there limitation to arrow function check this one
IDE is app that you use that help you to check your syntax like WebStorm: The JavaScript and TypeScript IDE, by JetBrains (you can use the bet version for free) and https://code.visualstudio.com/ and many more
Thank you so much
you very welcome