views:

100

answers:

2

I am creating an Image gallery and i want a few images to load when the next button is clicked.....
for example,

$("#next").css({cursor:"pointer"}).click(function(){
   //load image1,image2,image3
  });

HTML

<img src="image1.jpg"><img src="image2.jpg"><img src="image3.jpg">

i don't want to append them to a division, these image tags are already present in 'gallery' div tag... I just want to stop them from loading when the page loads at first and when the user clicks on next button theses images can load ...Thanks

A: 

Create img elements and add them to the DOM.

var img = $(document.createElement("img"));
img.attribute("src", "image1.jpg");
$("#mydiv").append(img);
August Lilleaas
i don't want to append them to a division, these image tags are already present in 'gallery' div tag... I just want to stop them from loading when the page loads at first and when the user clicks on next button theses images can load ...Thanks
halocursed
+2  A: 

If the images elements are already in your markup, and they have the src attribute defined, the image files will be downloaded when the page starts loading.

You should either create the image elements programmatically or leave the src attribute empty on your markup, and then assign it when the user clicks next.

Option 1:

// on the click event...
var images = ['img1.jpg', 'img2.jpg', 'img3.jpg'],
    gallery = $('#gallery');
$.each(images, function () {
  $('<img/>').attr('src', this).appendTo(gallery);
});

Option 2:

Markup:

<img id="img1"/> <img id="img2"/> <img id="img3"/>

On the click event:

$('#img1').attr('src', 'image1.jpg');
$('#img2').attr('src', 'image2.jpg');
$('#img3').attr('src', 'image3.jpg');

Edit:

Another option comes to my mind when you talk about lazy loading.

Option 3:

You could remove the src attribute of your images, and store it using the $.data function, then in your click event, restore the image src to its original value, for example:

$(function () {
  // put a "defaultImage" on all images of gallery
  // and store the original src attribute
  $('#gallery img').each(function () {
    $(this).data('originalSrc', $(this).src).attr('src', 'defaultImage.jpg');
  });

  $("#next").click(function(){
    $('#gallery img').each(function () {
      // restore the original src attribute:
      $(this).attr('src', $(this).data('originalSrc'));
    });
  });
});
CMS
so their is no way I can stop an image from loading if the src markup is defined... and I have to assign the src attributes when the user clicks next, if that's the case then thanks!!
halocursed
what about jquery lazy loading???
halocursed
Thanks a lot!!!
halocursed
You're welcome!
CMS