Onclick starts without clicking

en.onclick = setCookie('english');

Why does it start without even clicking on it?

I have 3 checkboxes that should set a cookie in their language when they click on the last one, which always fires immediately ...

+6
source share
4 answers

Your code above evaluates setCookie('english') and puts its return value (if any) in en.onclick . To assign it as an event handler, wrap it in a function:

 en.onclick = function(){ setCookie('english'); }; 
+18
source

you should use something like this

 en.onclick=function(){ setCookie('english'); } 
+4
source

Because you are calling the setCookie(...) method. Try the following:

 en.onclick = setCookie; 

Using parentheses, you call the method; without you passing it as an object.

Or try the following:

 en.onclick = function() { setCookie('english') }; 

Here we create a new function that calls setCookie with the appropriate argument.

+3
source

Good, because you use the method and assign the result to en.onclick.

What you probably want to make us

 en.onclick = function(){setCookie('english');}; 
+2
source

Source: https://habr.com/ru/post/886391/


All Articles