jQuery 'onImagesLoad' Plugin
Example 3 - Attaching to individual images
- Continuing from Example 2, it is not required that you attach onImagesLoad to an element that contains an image/images, but you can also attach directly to an individual image/images.
- In this example, the selector is $('.imageSection img'), which attaches to all images within all "imageSections":
- The 'all' callback will prepend red text in a yellow box at the top of the body when all images have loaded in all "imageSections".
- The 'each' callback will prepend red text in a yellow box at the top of each section when each individual image loads within it.
Code
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.onImagesLoad.js"></script>
<script type="text/javascript">
$(function(){
var eventNumber = 1; //so we can track the ordering of the events in the example
//attach directly to each image within each .imageSection
$('.imageSection img').onImagesLoad({
each : eachImgLoaded,
all : allImgsLoaded
});
//the 'each' callback is invoked once for each individual image that loads
//i.e. the 'each' callback will be invoked "$('.imageSection img').length" times
function eachImgLoaded(domObject){
//note: this == domObject. domObject will be the image element that has just finished loaded
$(domObject).parent().prepend('<div class="loaded">Event #'+(eventNumber++)+': Image ' + displayTxt(domObject) +
' has loaded. Displayed dimensions: ' + domObject.width + 'x' + domObject.height + '</div>');
}
//the 'all' is invoked only once: when all images that
//$('.imageSection img') encapsulates have loaded
function allImgsLoaded($selector){
//note: this == $selector. $selector is $('.imageSection img') here
var allLoaded = ""; //build a string of all items within the selector
$selector.each(function(){
allLoaded = displayTxt(this) + ', ';
})
$('body').prepend('<div class="loaded">Event #'+(eventNumber++)+': The following images have loaded within selector $("' +
this.selector + '"), which contains the following ' + $selector.length + ' items: ' + allLoaded + '</div>');
}
function displayTxt(domObject){ //helper function for displaying results
return '<' + domObject.tagName + (domObject.id ? ' id="' + domObject.id + '"' : '') + '>';
}
});
</script>
Images
<div id="imageSectionOne" class="imageSection">
<div id="imageSectionTwo" class="imageSection">