Connecting Tech Pros Worldwide Help | Site Map

how to correctly call a function

 
LinkBack Thread Tools Search this Thread
  #1  
Old August 16th, 2006, 05:35 PM
finerrecliner@gmail.com
Guest
 
Posts: n/a
Default how to correctly call a function

what i'm trying to accomplish:
user clicks button. then can click 2 more times anywhere on the page
and display his mouse coordinates. after those 2 clicks, go back to
normal mouse behavior

the code below does exactly that, but i dont understand how my click
function got the event argument, since i never passed anything to
it(see denoted line)? why does this work?

note: if i use the line document.onclick=click(e);
it won't work correctly, and will only call the click function when the
user clicks the button (rather than anywhere on the page).

<html>
<head>
<script type="text/javascript">
var x = 0;
function getcoords(e)
{
if (!e) var e = window.event;
document.onclick=click; //why does this line work?!
}
function click(e)
{
if(x == 0)
{
x = 1;
}
else if(x == 1)
{
alert(e.clientX + " , " + e.clientY);
x = 2;
}
else if(x == 2)
{
alert(e.clientX + " , " + e.clientY);
x = 0;
document.onclick=null;
}
else { alert("wtf");}

}
</script>
</head>
<body>
<button onclick="getcoords(event);">click here</button>
</body>
</html>


  #2  
Old August 16th, 2006, 06:15 PM
Martin Honnen
Guest
 
Posts: n/a
Default Re: how to correctly call a function



finerrecliner@gmail.com wrote:

Quote:
note: if i use the line document.onclick=click(e);
it won't work correctly, and will only call the click function when the
user clicks the button (rather than anywhere on the page).
Well that assignment calls the click function with an argument e (which
is probably not defined) and the result of that function call is
assigned to the document.onclick property.

Quote:
document.onclick=click; //why does this line work?!
Quote:
function click(e)
An event handler is a function and your assigment correctly assigns a
function, your click function, to the document.onclick property. The
browser then, when a click event occurs, calls that function, it is not
your code that has to call the function. And in the case of Mozilla the
browser passes in an event object as the first argument of the function.
For IE you need to use the window.event object as it does not pass in
the event object when it calls an event handler.


--

Martin Honnen
http://JavaScript.FAQTs.com/
 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,989 network members.