Jarco
Jarco

Reputation: 1775

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

Upvotes: 9

Views: 11832

Answers (4)

JohnP
JohnP

Reputation: 50029

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');};

Upvotes: 2

DarthJDG
DarthJDG

Reputation: 16591

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');
};

Upvotes: 25

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

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.

Upvotes: 3

Bick
Bick

Reputation: 267

cause you must use something like that

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

Upvotes: 5

Related Questions