How to Set OnClick attribute with value containing function in ie8?
157,113
Solution 1
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>
Solution 2
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!');
}
Solution 3
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
Solution 4
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);
Author by
edt
Updated on April 01, 2020Comments
-
edt over 4 years
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 Firefox 3, 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>