I have the following code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
function myFun()
{
alert(5)
}
$(document).ready(function(){
$("#myID").click(myFun());
})
</script>
</head>
<body>
<input type="button" value="Click it" id="myID" />
</body>
</html>
When I run this code then alert(5)
is coming when the page loads. If I write
$("#myID").click(myFun)
then the alert only appears when we click on the button. Why does it behave like this?
$("#myID").click(myFun());
This calls myFun()
and tries to install whatever it returns as an event handler. Since it is not returning anything, you are actually triggering the click on #myID
.
Read this .click() - Bind an event handler to the click
JavaScript event, or trigger that event on an element using JavaScript.
You just need to write $("#myID").click(myFun);
instead of $("#myID").click(myFun());
because when you write myFun()
in your code the function is invoked immediately (rather than when a click event fires on #myID
).
Try this for running the function on the click event:
function myFun(){
alert(5);
}
$(document).ready(function(){
$("#myID").click(function(){
myFun();
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With