Connecting Tech Pros Worldwide Forums | Help | Site Map

Loading image when scrollbar moves

Member
 
Join Date: Nov 2008
Posts: 39
#1: Jul 23 '09
Hi,
I have 500 images.when clicking on one link it need to load this much images.Its loading
fine.My requirement is load the image only in the viewable area.when scrolling the scrollbar next
viewable area need to be loaded what i need to do


Pls help me
Its urgent


Thanks in advance

gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,136
#2: Jul 23 '09

re: Loading image when scrollbar moves


so you have 500 images in one page? i would suggest a redesign to have some paging mechanism that is a bit more better to handle then. otherwise you would need to connect the scrolling-event to a load mechanism in a way that you react to the scrolloffset and calculate which images has to be loaded then. this is quite easy when all images have the same size and would be a bit more complicated when the (probably height) differs.

kind regards
Canabeez's Avatar
Member
 
Join Date: Jul 2009
Location: Israel
Posts: 85
#3: Jul 23 '09

re: Loading image when scrollbar moves


Here, try this, it should lead you to the right way.

Not sure how you can manage the src's, because you can't store them in the image and keep the image unloaded at the same time (Well, maybe you could store them as ALT text or a TITLE), but you decide.

But as gits said, if I were you, I'd consider redesign ;)

Good luck

Expand|Select|Wrap|Line Numbers
  1. function getPosition(Object)
  2. {
  3.     if('undefined' != typeof(Object.offsetParent))
  4.     {
  5.         for(var posX=0,posY=0;Object;Object=Object.offsetParent)
  6.         {
  7.             posX += Object.offsetLeft;
  8.             posY += Object.offsetTop;
  9.         }
  10.         return [posX,posY];
  11.     }
  12.     else
  13.     {
  14.         return [Object.x,Object.y];
  15.     }
  16. }
  17.  
  18. window.onscroll = function()
  19. {
  20.     var scrollTop = document.body.scrollTop;
  21.     var innerHeight = window.innerHeight;
  22.  
  23.     var images = document.getElementsByName("myImage");
  24.  
  25.     for(var i=0;i<images.length;i++)
  26.     {
  27.         var imageHeight = getPosition(images[i])[1];
  28.         if(imageHeight > scrollTop && imageHeight < (scrollTop + innerHeight))
  29.         {
  30.             images[i].src = images_src[i];
  31.         }
  32.     }
  33. }
  34.  
  35. var images_src = [];
  36.  
  37. for(var i=0;i<200;i++)
  38. {
  39.     images_src[i] = 'http://www.google.com/intl/en_ALL/images/logo.gif';
  40.     var img = document.createElement("img");
  41.     img.width = 276;
  42.     img.height = 110;
  43.     img.name = "myImage";
  44.     document.body.appendChild(img);
  45.     document.body.appendChild(document.createElement("br"));
  46. }
  47.  
Reply


Similar JavaScript / Ajax / DHTML bytes