Javascript – img onload examples

Sometime we need to call a function after an image has been loaded. We can attach onload even handler on image either in html itself or through dom object. Here are examples for these approaches.

Using onload in img tag html

<script type="text/javascript">
  function imgonload(obj) {
    document.querySelector("#log").innerHTML += "image loaded src=" + obj.src;
  }
</script>
<img src="/img/elephant1.jpg" onload="imgonload(this);" />
<div id="log"></div>
refresh

Using img element dom object onload

<div id="img1"></div>
<div id="log"></div>
<script type="text/javascript">
  function imgonload(obj) {
    document.querySelector("#log").innerHTML += "image loaded src=" + obj.src;
  }
  imgobj = new Image();
  imgobj.onload = function() {imgonload(imgobj);};
  imgobj.src = "/img/elephant1.jpg";
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments