I have the following code.... When the page is loaded myFunc() is called even if I dont click in my div. Why? The function declared "inline" is not triggered...hmmmm........
<div id="map" style="background: green; height: 100px"></div>
<script type="text/javascript">
function myFunc() {
alert("allways triggered when page loads...");
};
$(document).ready(function() {
$("#map").click(myFunc());
$("#map").click(function() { alert("not triggered") });
});
</script>
With the
myFunc()
in$("#map").click(myFunc())
you’re calling the function references bymyFunc
and only its return value is passed to$("#map").click
. If you want to pass themyFunc
function itself, leave the parenthesis away and use just the function name:You're calling your function in your click event handler. Do this instead:
You only pass the name of the function, without parenthesis, when passing it as an argument to an event handler (or any other function).
NOT
Because of your code:
is wrong and has to be:
Your code would call myFunc() first and than simulate a onclick event.
As seen in the documentation:
What you did is this: (as myFunc returns null)
What you want is this:
Should be
This way, you give the function as a parameter.
$("#map").click(myFunc());
triggered the function, and gives its result as a parameter.should be
and not
passing
myFunc()
instead ofmyFunc
actually invoke this function