Why is this happening...?!


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 :point_down: :

<button> Click Here</button>

JS :point_down: :point_down:

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 :point_down:

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 https://www.jetbrains.com/webstorm/ (you can use the bet version for free) and https://code.visualstudio.com/ and many more

1 Like

Thank you so much :green_heart:

you very welcome :slight_smile: