views:

2205

answers:

2

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>
+3  A: 

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!');
}
Jonathan Fingland
addEventListener and attachEvent are much better ways of adding events to DOM elements (including anchor tags). they are unobtrusive methods for adding an arbitrary number of events to elements, the onclick property, by contrast, only allows one event and is far more error prone (for example other scripts changing the property)
Jonathan Fingland
+3  A: 

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>
Hugoware
why put that in a closure? no reason for it that I can see.
Jonathan Fingland
Why write a separate function for alert('hello world')? :) -- It depends on what you're doing, a closure would be better IMO if you don't plan on calling it from other places.
Hugoware
in that case, no need for the function or closure. just document.getElementById("something").onclick = function() { alert('hello'); }; without any of the rest of it
Jonathan Fingland
Oh, you mean the self-executing function? There was no reason for it - I just wrote it that way so it would execute on start up.
Hugoware
Works perfect. Thanks!