9

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...

Jarco
  • 1,635
  • 4
  • 14
  • 22

4 Answers4

24

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');
};
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
  • Ok I understand. How can you tell the difference between one to pass somthing to a function (like you do here) Or evaluating it (like i did) – Jarco Apr 21 '11 at 12:16
  • 2
    @Jarco Since you're working with a callback you always need to give a function to be called. Event handlers always expect a callback. – JohnP Apr 21 '11 at 12:18
  • Probably a novice question: What do you mean by Callback? – Jarco Apr 21 '11 at 12:24
  • 1
    @Jarco: If there are brackets after the function name (with or without parameters), that means you're evaluating it. To pass a function as a function pointer, just use the name of the function. In my above example I created an anonymous inline function and put that function's pointer into en.onclick. – DarthJDG Apr 21 '11 at 12:26
  • Ok. Its just a matter of what is possible and what is not with javascript. Thanks. I understand this a lot better now. – Jarco Apr 21 '11 at 12:35
5

cause you must use something like that

en.onclick=function(){
  setCookie('english');
}
Bick
  • 267
  • 1
  • 7
3

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.

Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
2

Well that's because you're running the method and assigning the result to en.onclick.

What you probably want to do us

en.onclick = function(){setCookie('english');};
JohnP
  • 49,507
  • 13
  • 108
  • 140