how to correctly call a function

F

finerrecliner

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

Martin Honnen

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.

document.onclick=click; //why does this line work?!

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top