Skip to content

Instantly share code, notes, and snippets.

@karbassi
Created October 2, 2012 01:34
Show Gist options
  • Save karbassi/3815645 to your computer and use it in GitHub Desktop.
Save karbassi/3815645 to your computer and use it in GitHub Desktop.
This example showcases how to have an 'onload' function fire off for HTML <img> elements who are already loading in the HTML DOM.

This example showcases how to have an ‘onload’ function fire off for HTML <img> elements who are already loading in the HTML DOM.

Notice that the src is set to an empty string, the onload function is set, then the src is reset.

var imageOnLoad = function() {
var output = document.createElement('li');
output.innerText = 'Loaded #' + this.id + '. Size: '
+ this.width + 'px by ' + this.height
+ 'px. URL: ' + this.src;
var debug = document.getElementById('debug');
debug.appendChild(output);
};
var imgs = document.getElementsByTagName('img');
var l = imgs.length;
var i = 0;
for(; i < l; i++) {
var img = imgs[i];
var url = img.src;
img.src = '';
img.onload = imageOnLoad;
img.src = url;
}​
<!doctype html>
<html>
<head>
<title>.onload for html images</title>
<link rel="stylesheet" type="text/css" href="screen.css">
<script src="imageOnLoad.js"></script>
</head>
<body>
<div class="image-container">
<img src="http://placekitten.com/50/50" alt="" id="1" />
<img src="http://placekitten.com/60/75" alt="" id="2" />
<img src="http://placekitten.com/70/100" alt="" id="3" />
<img src="http://placekitten.com/80/125" alt="" id="4" />
<img src="http://placekitten.com/90/150" alt="" id="5" />
<img src="http://placekitten.com/100/175" alt="" id="6" />
<img src="http://placekitten.com/200/200" alt="" id="7" />
<img src="http://placekitten.com/300/225" alt="" id="8" />
</div>
<h2 class="main-header">Log</h2>
<ul id="debug">
</ul>
</body>
</html>
.image-container {
height: 300px;
width: 600px;
overflow: auto;
margin-bottom: 20px;
}
.main-header {
color: #F00;
font-size: 20px;
line-height: 26px;
border-bottom: 1px dashed #000;
margin-bottom: 5px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment