Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 an <A> link on initialization of the page.

When I run this I immediately get a 'foo' alert box where I expected to only get an alert when I click on the link.

What stupid thing am I doing wrong? (I've tried click= and onClick=)...

<script language="javascript">      function init(){          document.getElementById("foo").click = new function() { alert('foo'); };     }  </script>  <body onload="init()">     <a id="foo" href=#>Click to run foo</a> </body> 

Edit: I changed my accepted answer to a jQuery answer. The answer by 'Már Örlygsson' is technically the correct answer to my original question (click should be onclick and new should be removed) but I strongly discourage anyone from using 'document.getElementById(...) directly in their code - and to use jQuery instead.

like image 431
Simon_Weaver Avatar asked Oct 30 '08 02:10

Simon_Weaver


2 Answers

Try:

document.getElementById("foo").onclick = function (){alert('foo');}; 
like image 138
Christian C. Salvadó Avatar answered Sep 22 '22 06:09

Christian C. Salvadó


Use .onclick (all lowercase). Like so:

document.getElementById("foo").onclick = function () {   alert('foo'); // do your stuff   return false; // <-- 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.

like image 36
Már Örlygsson Avatar answered Sep 18 '22 06:09

Már Örlygsson