Skip to content Skip to sidebar Skip to footer

How To Change Onclick Handler Dynamically?

I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something. I have a simple script where I want to set the onClick handler for

Solution 1:

Try:

document.getElementById("foo").onclick = function (){alert('foo');};

Solution 2:

Use .onclick (all lowercase). Like so:

document.getElementById("foo").onclick = function () {
  alert('foo'); // do your stuffreturnfalse; // <-- to suppress the default link behaviour
};

Actually, you'll probably find yourself way better off using some good library (I recommend jQuery for several reasons) to get you up and running, and writing clean javascript.

Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.

Solution 3:

jQuery:

$('#foo').click(function() { alert('foo'); });

Or if you don't want it to follow the link href:

$('#foo').click(function() { alert('foo'); returnfalse; });

Solution 4:

I tried more or less all of the other solutions the other day, but none of them worked for me until I tried this one:

var submitButton = document.getElementById('submitButton');
submitButton.setAttribute('onclick',  'alert("hello");');

As far as I can tell, it works perfectly.

Solution 5:

If you want to pass variables from the current function, another way to do this is, for example:

document.getElementById("space1").onclick = newFunction("lrgWithInfo('"+myVar+"')");

If you don't need to pass information from this function, it's just:

document.getElementById("space1").onclick = newFunction("lrgWithInfo('13')");

Post a Comment for "How To Change Onclick Handler Dynamically?"