My goal is to change the "onclick" attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3.
For example, this works in firefox3, but not ie8. Why???
<p><a id="bar" href="#" onclick="temp()">click me</a></p>
<script>
doit = function(){
alert('hello world!');
}
foo = document.getElementById("bar");
foo.setAttribute("onclick","javascript:doit();");
</script>
You don't need to use setAttribute for that - This code works (IE8 also)
<div id="something" >Hello</div>
<script type="text/javascript" >
(function() {
document.getElementById("something").onclick = function() {
alert('hello');
};
})();
</script>
your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too.
.....
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);