Friday, August 1, 2008

Img tag onLoad function problem in internet explorer

Few days ago i had a problem with onLoad in img tag in ie. Interestingly the same code works with firefox. Anyway i found the solution that works both browsers.

Below is the code that should display(load) the google image and then enable the button.

<html>

<head>
<script type="text/javascript">

function loadImage(){
var div1 = document.getElementById('imgdiv1');
var img1 = document.createElement('img');
var attr = document.createAttribute('onLoad');
attr.value = 'onLoadImg()';
img1.setAttributeNode(attr);
img1.src='http://www.google.co.in/intl/en_com/images/logo_plain.png';
div1.appendChild(img1);
}

function onLoadImg(){

var subBut=document.getElementById('flag');
subBut.disabled = false;
}

function onLoadFun(image){
loadImage();
}
</script>
</head>
<body onLoad='onLoadFun()'>
<div id="imgdiv1" ></div>
<input type="submit" id="flag" value="Disable" disabled="true"/>
</body>
</html>


This works fine with firefox, but in ie button is not enabled, which impiles onLoad function is never got invoked.
But a small change worked well for both the browsers. Instead of providing the onLoad function name, assign the reference.

attr.value = onLoadImg;

No comments: