Changing onclick event with broken javascript

I have it:

function tp_visible(action){ if(action==1){ document.getElementById("tp").style.display='block'; document.getElementById("tp_action").onclick='tp_visible(0); return false;'; } else { document.getElementById("tp").style.display='none'; document.getElementById("tp_action").onclick='tp_visible(1); return false;'; } return false; } 

Why doesn't this mean changing the onclick event?

I am using Firebug and the event remains the same ...

Here is the HTML:

 <a id='tp_action' name='tp_action' href='#' onclick='tp_visible(1); return false;' >Show info</a> 
+4
source share
2 answers

The check below will work for you because you cannot assign a string value to the onclick handler.

 function tp_visible(action){ if(action==1){ document.getElementById("tp").style.display='block'; document.getElementById("tp_action").onclick= function () { tp_visible(0); return false;}; } else { document.getElementById("tp").style.display='none'; document.getElementById("tp_action").onclick= function () {tp_visible(1); return false; } } return false; } 
+10
source

If you start with Javascript, I suggest you get to know one of the many excellent javascript libraries and never try to write this stuff again for yourself - this leads to a loss of consciousness.

You could also do worse than buy Javascript The Good Bits and watch a set of Douglas Crockford videos.

0
source

All Articles