javascripthtmlruby-on-railsimgix-jsimgix

How to apply imgix-js on command?


$(document).ready(function () {
    var imgixOptions = {
        updateOnResizeDown : true,
        updateOnPinchZoom : true,
        fitImgTagToContainerWidth: true,
        fitImgTagToContainerHeight: true,
        autoInsertCSSBestPractices: true,
        pixelStep : 5
    };

    imgix.onready(function() {
        imgix.fluid(imgixOptions);
    });
});

This works as expected on dom ready however some pieces of my site load dynamically using AJAX.

How can I trigger the imgix-js library to load the images the way it does on dom ready?


Solution

  • You'll need to call imgix.fluid on the new content after the AJAX load completes, passing in the parent node of the new content to limit the scope of the new .fluid call. Something like this:

    // Store the target that your async content is being inserted into
    var $target = $('#target');
    
    // Make your AJAX request
    $target.load('new_content.html', function () {
      var imgixOptions = {
        updateOnResizeDown : true,
        updateOnPinchZoom : true,
        fitImgTagToContainerWidth: true,
        fitImgTagToContainerHeight: true,
        autoInsertCSSBestPractices: true,
        pixelStep : 5
      };
    
      // Call imgix.fluid, passing the target as the rootnode.
      // Note that imgix.fluid expects the rootnode to be an HTMLElement
      // rather than a jQuery collection, so call .get(0) on $target
      imgix.fluid($target.get(0), imgixOptions);
    });
    

    I totally recognize that this isn't very intuitive at the moment--you've already called imgix.fluid() at the document level earlier, so marking these new images as fluid independently doesn't smell quite right. We're aware of this limitation and will figure out a way to make this work better in a future version of the library. If you've got specific ideas on how you think this behavior should be handled, you should email me at jason@imgix.com and I'd be happy to discuss!