Search code examples
phphtmlexpand

PHP: Don't load images until div is expanded?


On my site, I have an updates section, which groups updates (galleries) into their own div. Each div is loaded hidden. They choose a section, and it expands to show the new galleries.

That all works fine. However, it loads all the images on the page load, which causes the hour glass to linger longer than I like. Is there any way to make an image load after a div is made visible?

Edit:

Went with:

    $(function() {
      $('.collapse img').attr('src', function(index, src) {
         return this.getAttribute('data-src');
      });
    });

collapse is the div name that has the images in it. How can this be changed to only change the images in that current div? All the collapsed divs have the same name. However, when expanded, I want it to load only the images in that one div. Right now it loads all the images in all the collapsed div once I expand one of them.


Solution

  • Your divs should not contain the images at startup. You can load the images via JavaScript if a user expands your div.

    Example:

    function expandDiv(idOfDivElement) {
        divObj = document.getElementById(idOfDivElement);
        var imageObj = document.createElement('img');
        imageObj.setAttribute('src', 'path/example_image.jpg');
        divObj.appendChild(imageObj);
        // your expand div code here
    }
    

    You could advance this function and add a second parameter for the image url. Or a array / comma seperated string if you want to load multiple images.