[Javascript] onclick and functions

Paul Novitski paul at juniperwebcraft.com
Sat Aug 12 10:08:24 CDT 2006


At 07:27 AM 8/12/2006, tedd wrote:
>http://xn--ovg.com/a9.php

>1. Why do the alerts show at start-up?

Because you tell them to:

         a.onclick = test1(1);
         b.onclick = test2();

What you want is:

         a.onclick = test1;
         b.onclick = test2;

It's the *content* of the function that we attach to a behavior.  This code:

         a.onclick = test1;

         function test1(c)
                 {
                 var d = c + 1;
                 alert(d);
                 }

sets a.onclick equal to "var d = c + 1; alert(d);".  Try coding:

         alert(test1);

and see what you get (note the absence of () parens after test1).

Including the parentheses actually calls the function in the moment:

         a.onclick = test1(1);

is going to set a.onclick equal to the result of running the function 
test1(2) -- in this case, null, since you're not returning any value 
from the function.


>2. Why does the onclick not work (i.e., no alerts)?

Because you haven't properly registered the functions to execute onclick.


>I spent a lot of time trying to find a reference, but couldn't find 
>anything regarding this. Everything I read suggested that this should work.

Try going back to the well:

Gecko DOM Reference
http://developer.mozilla.org/en/docs/DOM:element.onclick

Notice there are no parentheses in the onclick statement.  I imagine 
that if you look at your other sources closely again you'll see that 
they conform.


>What I simply want to do is to call a function (while passing a 
>variable) by clicking a div.

That's tricky (the variable part).  Do you want the passed value to 
vary from one click event to the next?  If so, defining it when you 
set the onclick behavior won't work because you're effectively 
freezing the argument value in time.

If the argument to the function never varies, why pass it at 
all?  Why not just have it as a static value set within the function?

If the argument to the function does vary, I suggest you omit it as a 
function argument and instead use, say, a global variable:

         var gblSomething;
         ...
         a.onclick = test1;
         ...
         gblSomething = 4;
         ...
         gblSomething = 25/7;
         ...

         function test1()
                 {
                 var d = gblSomething + 1;
                 alert(d);
                 }


Regards,
Paul





More information about the Javascript mailing list