...

View Full Version : function syntax error??



samz
09-15-2011, 03:00 AM
why does my javascript function run right away when the page loads? but not wen the button is clicked? its working the opposite to how i want it to :(
i didnt include the other html tags to help focus on this.
Btw im tryna avoid the method of having the onclick="funct()" method which would be written in the button tag. Thank you.

<body>
<button id="mybutton">Click me</button>
</body>

<script type = "text/javascript">
var b = document.getElementById("mybutton");
b.onclick = funct()

function funct()
{
alert("Thanks for clicking me!");
}
</script>

Old Pedant
09-15-2011, 04:17 AM
<script type = "text/javascript">
// function defined first, so the assignment below knows what it is
function funct()
{
alert("Thanks for clicking me!");
}
var b = document.getElementById("mybutton");
// assign the *function* to the onclick, *NOT* the result of CALLING the function
b.onclick = funct;

</script>

samz
09-15-2011, 06:10 AM
you sir are a LEGEND:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum