I have code like
<a id='lnk1' onclick='do something' >test</a>
Later on code is added to the same anchor tag like
lnk = document.getElementById('lnk1')
lnk.onclick = function() { do something}
Now what is happening is that in the second piece of code the onclick function of the anchor tag is getting overwritten. What I want to happen instead is that the first onclick's code is run and after that the 2nd onclick's is run.
You could try this:
That code saves a reference to the old handler, and if it's not empty it calls it before doing whatever else the new handler wants to do.
You could put the call to the old handler after the new code, or mixed in, or whatever.
JavaScript
when setting onclick you are overwrite existing attribute, but assign click through event listener then it will be ok.
There is a very simple, standards-compliant way to do this:
This doesn't work in IE before version 9, so you'll need to do this:
This will work, and both the original function specificed in the HTML attribute and in the code above will run. HOWEVER it would be far nicer to define all your event handlers in the same place: in the Javascript. Think hard about removing event handling logic from your HTML attributes.
You have a mistake in your statement:
JAVASCRIPT
You have defined
lnk
as variable but your are callinglnk1
withonclick
event. This is a wrong statement.USE HTML
See the Demo: http://jsfiddle.net/tm5cX/