Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onclick gets fired without clicking

en.onclick = setCookie('english');

Why does this get fired without even clicking on it?

I have 3 flags that should set a cookie to their language when clicked wit the last one always gets fired right away...

like image 648
Jarco Avatar asked Apr 21 '11 12:04

Jarco


3 Answers

Your code above evaluates setCookie('english') and puts its returned value (if any) into en.onclick. In order to assign it as an event handler, wrap it into a function:

en.onclick = function(){
   setCookie('english');
};
like image 63
DarthJDG Avatar answered Nov 01 '22 22:11

DarthJDG


cause you must use something like that

en.onclick=function(){
  setCookie('english');
}
like image 5
Bick Avatar answered Nov 01 '22 22:11

Bick


Because you're invoking the method setCookie(...). Try this:

en.onclick = setCookie;

With the brackets you're invoking the method; without you're handing it as an object.

Or try this:

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

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

like image 3
Richard JP Le Guen Avatar answered Nov 01 '22 23:11

Richard JP Le Guen