Jump to content

the humble onclick...


Kreplock

Recommended Posts

i was hoping to make button functions dynamic by changing the onclick property on the fly. i'm starting to think JS won't let me. simple example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>A Test Page</title><script language="JavaScript" type="text/javascript"><!--function clicky() {	alert("clicky");	aForm.aBn.value = "clicked";	aForm.aBn.onclick = "unClicky()";}function unClicky() {	alert("unclicky");	aForm.aBn.value = "clicky";	aForm.aBn.onclick = "clicky()";}//--></script></head><body><form name="aForm">	<input type="button" name="aBn" value="clicky" onclick="clicky()"></form></body></html>

can any tell me what's wrong there, or if it's illegal and why?

Link to comment
Share on other sites

When assigning event handlers through the DOM, you're actually assigning a reference to a function rather than calling the function. So, rather than:

aForm.aBn.onclick = "unClicky()";

You'll want:

aForm.aBn.onclick = unClicky;

Link to comment
Share on other sites

i hate to be helpless, but i updated my code and get the same behavior (nothing happens on the second click). also, i'm wondering how you would pass arguments using an onclick updated through the DOM?

function clicky() {	alert("clicky");	aForm.aBn.value = "clicked";	aForm.aBn.onclick = "unClicky";}function unClicky() {	alert("unclicky");	aForm.aBn.value = "clicky";	aForm.aBn.onclick = "clicky";}

Link to comment
Share on other sites

Rather than assigning a string (e.g. "unClicky"), you need to assign a reference (e.g. unClicky).

<html><body><button id="myButton">Click Me</button><script type="text/javascript">var myButton = document.getElementById("myButton");function handleClick(){    myButton.innerHTML = "You clicked it!";    myButton.onclick = handleUnClick;}function handleUnClick(){    myButton.innerHTML = "Click Me";    myButton.onclick = handleClick;}myButton.onclick = handleClick;</script></body></html>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...