• Home
  • Services
  • Profile
  • Portfolio
  • Contact
  • Links
  • Blog
  • Archives
  • Sitemap
Subscribe: Posts | Comments | E-mail
  • Ajax XMLHttpRequestAsynchronous HTTP Request How To's
  • FreebiesBest Freebies Collection
  • MiscellaneousNews, Announcements & General Stuffs
  • Print & Web DesignPhotoshop, Vector, CSS, XHTML
  • ProgrammingProgramming PHP, ASP, .NET and more

Bali Web Design

Posted on September 8, 2008 - by webmaster

Jquery Image Loader

Freebies Tutorials

jquery_image_load

Found a tutorial about image loading using Jquery written by Remy Sharp while trying to create the same function for company i am working at. Remy has publish the core script and here i will modify it to make it work for multiple images, and load in sequencing order.

Multiple Image Loading

First we create an HTML page which has list element with class “loading” which we’re going to define later in the CSS, the amount of the list element depend on how many images we need to put here, in this example i have 3 images.

	<ul id="portfolio">
	<li class="loading"></li>
	<li class="loading"></li>
	<li class="loading"></li>
	</ul>

Next we add CSS for “loading” class which contain the spinner animated gif, as the loading animation.

<style type="text/css">
ul#portfolio { margin:0; padding:0; }
ul#portfolio li { float:left; margin:0 5px 0 0; width:250px; height:250px; list-style:none; }
ul#portfolio li.loading { background: url(spinner.gif) no-repeat center center; }
</style>

and here is the javascript, i already put some comments, which explain what the block codes do. Dont forget to load the jquery core file before these block lines.

// DOM ready
$(function () {

			// image source
			var images = new Array();
				images[0] = 'http://farm4.static.flickr.com/3293/2805001285_4164179461_m.jpg';
				images[1] = 'http://farm4.static.flickr.com/3103/2801920553_656406f2dd_m.jpg';
				images[2] = 'http://farm4.static.flickr.com/3248/2802705514_b7a0ba55c9_m.jpg';

			// loop through matching element
			$("ul#portfolio li").each(function(index,el){
					// new image object
			        var img = new Image();
					// image onload
			        $(img).load(function () {
						// hide first
			            $(this).css('display','none'); // since .hide() failed in safari
						//
			            $(el).removeClass('loading').append(this);
			            $(this).fadeIn();
			        }).error(function () {
						$(el).remove();
			        }).attr('src', images[index]);
			});

		});

you can see the preview of what we did so far here

Create element programmaticaly

Because of sometimes we do not know how many images will be added there, so its better if we let the codes to create the element itself, as many as neccesary. First lets change the HTML codes and left the UL alone with no child.

<ul id="portfolio"></ul>

and we need to change the looping part of the javascript:

			// loop through images
			$(images).each(function(index,value){
					// create the LI programatically
					var list = $('<li id="portfolio_'+index+'"></li>').attr('class','loading');
					// append the new LI to UL
					$('ul#portfolio').append(list);
					// current LI object
					var curr = $("ul#portfolio li#portfolio_"+index);
					// new image
			        var img = new Image();
					// load image
			        $(img).load(function () {
			            $(this).css('display','none'); // since .hide() failed in safari
			            $(curr).removeClass('loading').append(this);
			            $(this).fadeIn();
			        }).error(function () {
						$(curr).remove();
			        }).attr('src', value);
			});

Whats the different?, well on the first part the loop is based on matching element, and load the image from the array based on the index of the element, here the loop is based on the images array, and create the LI element programmaticaly for each of them, and then load itself to the new LI element.

and here is the preview

Sequencing Image Load

At the both previous examples all the images are loaded almost at the same times, now we will make the next image loaded only after the previous ones loaded or could not loaded (error).

Here is the HTML block:

<div id="wrapper"></div>

and here are the final javascript codes:

		// DOM Ready
		$(function () {
			// Image Sources
			var images = new Array();
				images[0] = 'http://farm4.static.flickr.com/3293/2805001285_4164179461_m.jpg';
				images[1] = 'http://farm4.static.flickr.com/3103/2801920553_656406f2dd_m.jpg';
				images[2] = 'http://farm4.static.flickr.com/3248/2802705514_b7a0ba55c9_m.jpg';
			// images length
			var max = $(images).length;
			// at least 1 image exist
			if(max>0)
			{
				// create the UL element
				var ul = $('<ul id="portfolio"></ul>');
				// append to div#wrapper
				$(ul).appendTo($('#wrapper'));
				// load the first image
				LoadImage(0,max);
			}

			// function of loading image
			// params: (int) index of image in array, (int) length of images array
			function LoadImage(index,max)
				{
					// if current index is lower then max element (max-1)
					if(index<max)
						{
							// create the LI, add loading class
							var list = $('<li id="portfolio_'+index+'"></li>').attr('class','loading');
							// append to UL
							$('ul#portfolio').append(list);
							// current LI
							var curr = $("ul#portfolio li#portfolio_"+index);
							// new image object
					        var img = new Image();
							// image onload
					        $(img).load(function () {
					            $(this).css('display','none'); // since .hide() failed in safari
					            $(curr).removeClass('loading').append(this);
					            $(this).fadeIn('slow',function(){
										// once the current loaded, trigger the next image
										LoadImage(index+1,max);
									});
					        }).error(function () {
								// on error remove current
								$(curr).remove();
								// trigger the next image
								LoadImage(index+1,max);
					        }).attr('src', images[index]);
						}
				}

		});

What the changes we made?, we completely changed the load method. Here we use a function “LoadImage” to load the image one by one based on the index of the image as the parameter.

	if(max>0)
	{
		// create the UL element
		var ul = $('<ul id="portfolio"></ul>');
		// append to div#wrapper
		$(ul).appendTo($('#wrapper'));
		// load the first image
		LoadImage(0,max);
	}

you probably knew what the code above does, it check if image sources at least has 1 image, if so then it create UL element, and append it to div with id=”wrapper”, and then load the first image.

$(this).fadeIn('slow',function(){
		LoadImage(index+1,max);
});

once the current image has completely loaded we trigger the same function to load the next image

and here is the final preview.

Experiments

Take a look at my Flickr Photo Set, uses PHP Flickr API, and the Jquery Image Loader above.

Small Update

Small update about grabbing the images from the DOM instead of declare it manualy at the javascript codes, could be found here, thanks for commenting :)

Share this article:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • MySpace
  • Ping.fm
  • Pownce
  • Slashdot
  • StumbleUpon
  • Technorati
  • Tumblr
  • TwitThis
This entry was posted on Monday, September 8th, 2008 at 17:19 and is filed under Freebies, Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

33 Comments

We'd love to hear yours!



  1. Visit My Website

    September 13, 2008

    Permalink

    jQuery image loader, in webtoolkit4.me said:

    [...] chazzuka.com released a tutorial using jQuery about loading images in a sequential order. The tutorial is actually a modification of image loading using jQuery by Remy Sharp. Have a look at the tutorial and the demo of this script. [...]



  2. Visit My Website

    September 18, 2008

    Permalink

    ajusspy said:

    hehehe just for shared bro, i can take de source url after the tutorial, cpy paste but by editing and learning….btw jarain bro klo bisa… ente kan tau lebih awal…..



  3. Visit My Website

    September 18, 2008

    Permalink

    demonita said:

    @ajus
    well np, but keep the link instead of plain text and hoping the visitor to copy paste, you got the advantage from the content, and the author got it from the link :) win2win. be wise. mari belajar sama2



  4. Visit My Website

    September 24, 2008

    Permalink

    anand said:

    Can we make this to the content which will load in the same page which is coming from the database.



  5. Visit My Website

    September 24, 2008

    Permalink

    Komang said:

    absolutely yes, if you know how to ajaxed with jquery, you need to change the loadimage function:
    $.get(file_url,{parameters: value},function(data){
    … remove the loading style
    … display your content in the container
    })



  6. Visit My Website

    September 26, 2008

    Permalink

    ghozan said:

    great article bro, it’s a very nice way of loading images in your blog pages. will try it soon!



  7. Visit My Website

    September 26, 2008

    Permalink

    demonita said:

    Great to find ppls like to use it, thanks for dropping by :)



  8. Visit My Website

    September 29, 2008

    Permalink

    avinash said:

    hello,
    http://www.chazzuka.com/experiments/jquery-image-loader/jquery-image-loader-3.html

    this is the broken link on the site…for jquery image loader



  9. Visit My Website

    September 29, 2008

    Permalink

    Komang said:

    @avinash
    just check it out, and the page is exist but thanks anyway



  10. Visit My Website

    October 6, 2008

    Permalink

    jeff said:

    hi;

    nice script man ! is it possible to load a php/html page insteaf of images ?

    thanks
    jell



  11. Visit My Website

    October 6, 2008

    Permalink

    chris said:

    very very nice!

    I´m trying to use this script to combine with a lightbox or something simlar, so I need to link the images. Is this possible?

    thank you



  12. Visit My Website

    October 6, 2008

    Permalink

    Komang said:

    @jeff
    ofcourse you can, but certainly you need to make some modifications, i suggest you to read http://www.chazzuka.com/blog/?p=246 and change the loading style, and you done.

    @chris
    it is possible, once the image loaded you can wrap() it with links and then trigger the lightbox initialization for the image



  13. Visit My Website

    October 6, 2008

    Permalink

    chris said:

    ah ok,
    well i`m absolutely new to javascript. can you help me how to wrap the links arround the image? via javascript as well or in html?



  14. Visit My Website

    October 9, 2008

    Permalink

    Rob Record said:

    Hey that’s a great tutorial man! Thanks a lot. I am using it in my latest web project – a photography gallery using sliding navigation. This is just what I need for loading the images.

    Next I have to figure out how to get the width and height of the images so I can scale them to make thumbnails. Any ideas about getting these attributes, off the top of your head? I will try to work it out anyway.

    Thanks again!



  15. Visit My Website

    October 9, 2008

    Permalink

    Rob Record said:

    Chris,

    If you want to adapt this code to your needs, I suggest you learn the basics of jQuery and javascript first or you will be in for a hard time. There are a lot of nice beginners tutorials out there. Don’t skip the basics or it will be harder for you to de-bug your code.

    What you want to do is documented here: http://docs.jquery.com/Manipulation/wrap

    Hope that helps.



  16. Visit My Website

    October 9, 2008

    Permalink

    Komang said:

    @rob
    i think the best way is use server side to resize the image, but if you want to resize it with javascript this code will resize image proportionaly based on static maximum dimension

    if($(this).width() > $(this).height()) {
    $(this).css(‘width’,MaxPreviewDimension+’px’);
    $(this).css(‘height’,'auto’);
    } else {
    $(this).css(‘height’,MaxPreviewDimension+’px’);
    $(this).css(‘width’,'auto’);
    }



  17. Visit My Website

    October 10, 2008

    Permalink

    chris said:

    hey rob,
    thanks for your reply…

    i took a look at documentation and the “wrap”… seems easy when reading. but impossible to implement. cause i do not only need to wrap the tags around the images but to define the hyperlinks as well. do i have to put them in an array, too?



  18. Visit My Website

    October 11, 2008

    Permalink

    demonita said:

    @chris
    simply add the hyperlink directly in the tag at the wrap command
    $(el).wrap('<tag attribute=""></close_tag>');



  19. Visit My Website

    November 16, 2008

    Permalink

    My web notables… | Folks Pants Unlimited Love & Peace Project said:

    [...] Jquery Image Loader Found a tutorial about image loading using Jquery written by Remy Sharp while trying to create the same function for company i am working at. Remy has [...]



  20. Visit My Website

    January 6, 2009

    Permalink

    50+ jQuery Tutorials und mehr für Einsteiger und Fortgeschrittene said:

    [...] jQuery Image Loader Loader für mehrere Bilder. [...]



  21. Visit My Website

    January 8, 2009

    Permalink

    Eyveneena said:

    Thank you for taking the time to prepare this tutorial for everyone. I like the way you described the process of the code in detail. Being new to the idea of jQuery (which I love, since i am new to javascript), i needed to understand the process of loading many images at once and to be able to understand the creating of list and appending it to the “ul” that is appended to the divider makes it seem so much more professional and less time coding. After all, it is the finished product that gives us the satisfaction. I don’ t know about everyone else but I am not very patient to see my artwork finished and get the compliments…:). jQuery makes this possible, so…Thank you seriously…I feel like i have learned a professional way to upload images into the jQuery application.

    Eyveneena



  22. Visit My Website

    January 8, 2009

    Permalink

    Eyveneena said:

    re:”Next I have to figure out how to get the width and height of the images so I can scale them to make thumbnails. Any ideas about getting these attributes, off the top of your head? I will try to work it out anyway.”

    …if you make a wrapped container for the image and set it to the size of the thumbnail or image size then code your image width to 100% it will display the way you want it to.

    Eyveneena



  23. Visit My Website

    January 24, 2009

    Permalink

    Aaron B said:

    This is great!

    Is it possible to make it load any image in a div and not have to add them manually?

    I want to have this fade in images on a page if there are any images in a div with a class or id.

    so instead of doing this…

    // Image Sources
    var images = new Array();

    I want it to dynamically look at the div and get all images on the page and then load them and fade them in.

    Is this possible?

    Thanks sooooo much for the help!



  24. Visit My Website

    January 29, 2009

    Permalink

    Johan said:

    @Aaron B
    That’s exactly what i’m looking for too!… But with the images wrapped with a-tags.

    Can some please tell me how this is done?



  25. Visit My Website

    January 30, 2009

    Permalink

    Komang said:

    @Aaron, @Johan

    Ofcourse it is possible you only need to change the way you populate the images variable,
    for example if you need to grab the images from the li tags

    var images = $(‘li img’);

    then you need to modify the source of where the image should be loaded, it will become

    .attr(’src’, $(images[index]).attr(’src’)

    one note is you need to tell the bowser to not load those image immedietely probably by removing them just after grabs the images var



  26. Visit My Website

    January 30, 2009

    Permalink

    Komang said:

    Ok guys here are the changes that you asked for
    http://www.chazzuka.com/blog/?p=306



  27. Visit My Website

    April 15, 2009

    Permalink

    Alexander said:

    All is fine, but these examples do not work in Opera 9. Especially “glitch” an example 3 most interesting. They “break” on a method “fadeIn”. Though at me on a site “http: // tatiana-art.ru/main.html? 0.9887964962981641L1|P1|T7|” this method works on Opera 9.
    In what there can be a reason?



  28. Visit My Website

    May 20, 2009

    Permalink

    Ben said:

    Hi,

    Thanks for this plugin.
    post 306 doesn’t exist, it’s 103 (http://www.chazzuka.com/blog/?p=103)



  29. Visit My Website

    October 8, 2009

    Permalink

    78 jQuery Scenarios to Fall in Love | ProgrammerFish – Everything that’s programmed! said:

    [...] 21)jQuery image loader [...]



  30. Visit My Website

    October 27, 2009

    Permalink

    ersin said:

    Thanks for this great tutorial



  31. Visit My Website

    February 4, 2010

    Permalink

    bz said:

    Hi,
    I was interested in “Small update about grabbing the images from the DOM” but couldn’t find anything cause of page error. Where may I find something about it? Thanks!

    P.S. great job



  32. Visit My Website

    February 21, 2010

    Permalink

    master said:

    Hi,
    I was interested in “Small update about grabbing the images from the DOM” but couldn’t find anything cause of page error. Where may I find something about it? Thanks!



  33. Visit My Website

    March 12, 2010

    Permalink

    Hassan said:

    the correct url for the update that Remy sharp made is
    (http://www.chazzuka.com/blog/?p=103)
    also it includes example of what u all looking for.



Leave a Comment

Here's your chance to speak.

  1. Name (required)

    Mail (required)

    Website

    Message

  • Most Popular Posts

    • { 108 } ResponsesPHP ajax login form using Jquery
    • { 79 } Responsesphp ajax tutorial create ajax based login form using jquery
    • { 71 } ResponsesASP Classic Programming Still Alive
    • { 53 } Responses63+ best practice to optimize PHP code performances
    • { 44 } ResponsesVideobox: Lightbox for videos
  • Latest Posts

    • PHP Newbie: Proper handling of Error & Exception in PHP
    • Why SEO lost importance
    • jQuery Mobile Announced : Touch-Optimized Web Framework for Smartphones & Tablets
    • Multiple Google Account Signin
    • Install, Configure & Running Memcache in Windows as Service
    • DynamicWP Image Cube Wordpress Plugin
    • New Wordpress 3.0 API menu_page_url
    • Wordpress 3.0 Custom Taxonomy
    • JQuery DataGrid Plugin Compass
    • Upgrading to upcoming CodeIgniter 2.0
  • Categories

    • advertorial
    • Ajax XMLHttpRequest
    • Featured
    • Freebies
    • Miscellaneous
    • Print & Web Design
    • Programming
    • Tutorials
    • Web 2.0
  • Featured News

    • PHP Newbie: Proper handling of Error & Exception in PHP by webmaster on August 18, 2010
    • Why SEO lost importance by webmaster on August 16, 2010
    • jQuery Mobile Announced : Touch-Optimized Web Framework for Smartphones & Tablets by webmaster on August 16, 2010
    • Install, Configure & Running Memcache in Windows as Service by webmaster on June 27, 2010
    • Website Optimization Best Practices, speed up your website load by ruby on May 21, 2009
  • Tag Cloud

    • Actionscript advertorial Ajax XMLHttpRequest API best practices CakePHP chat Classic ASP CMS CSS Development facebook firefox Flash flickr Freebies gmail HTML icons Javascript Jobs jQuery jQuery Plugins Library Lightbox memcache Mootools news Personal PHP PHP Frameworks plurk Print & Web Design prism Prototype regex regular expression Scriptaculous SEO Tutorial twitter Web 2.0 Wordpress Works YUI
  • Archives

    • August 2010
    • June 2010
    • May 2010
    • September 2009
    • June 2009
    • May 2009
    • April 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • September 2008
    • August 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • March 2008
    • February 2008
    • January 2008
    • December 2007
    • November 2007
    • October 2007
copyleft 2007 - 2010 Bali Website Design Studio