EzDevInfo.com

imagesloaded

JavaScript is all like "You images done yet or what?" ImagesLoaded

Test imagesLoaded() progress callback using jasmine

I have the following code:

    $.ajax({
      url: API + "item/" + item_id.replace('-',':'),
      beforeSend: function(xhr){xhr.setRequestHeader('x-customer', customer);},
      format: "json",
      success: function( data ){
          var template_name =  data.source + settings.overlay_style;
          $('#modal .modal-content').html(Handlebars.templates[template_name](data));

        /* Handle missing avatars */
        $('#modal-avatar-image').imagesLoaded()
            .progress( function( instance, image ) {
                if (!image.isLoaded) {
                    image.img.src = "/images/404_avatar.svg";
                    image.img.alt = "The avatar for this user could not be found. Showing placeholder";
                    image.img.title = "The avatar for this user could not be found. Showing plac eholder";
                }
            });

        /* Handle missing main content */
        $('.modal-img').imagesLoaded()
            .progress( function( instance, image ) {
                if (!image.isLoaded) {
                    image.img.src = "/images/404_image.svg";
                    image.img.alt = "This image is lost in space. Could be removed by user or could be lost in a remote tube";
                    image.img.title = "This image is lost in space. Could be removed by user or could be lost in a remote tube";
                }
                $('.modal-img').removeClass('loading');
            });
});

I have wrote several tests for this block of code, but I cannot seem to get it to execute:

 var attrs = ['src', 'alt', 'title'];

           attrs.forEach( function(attr, idx, arr) {
                it('should set default ' + attr + ' for img#modal-avatar-image', function () {
                    spyOn($, 'ajax').and.callFake(function(e){
                        e.success({'source': 'twitter'});
                    });
                    openModal('test');
                    expect(val).toBeDefined();
                    val = $($("#modal-avatar-image")[0]).attr(attr);
                    if(attr === 'src'){
                        //expect the src to chnage from the old value
                        expect(val !== src).toBeTruthy();
                    }
                });
            });

            attrs.forEach( function(attr, idx, arr) {
                it('should set default ' + attr + ' for img.modal-img', function () {
                    spyOn($, 'ajax').and.callFake(function(e){
                        e.success({'source': 'twitter'});
                    });
                    openModal('test');
                    val = $($(".modal-img")[0]).attr(attr);
                    expect(val).toBeDefined();
                    if(attr === 'src'){
                        //expect the src to chnage from the old value
                        expect(val !== src).toBeTruthy();
                    }
                });
            });

Output:

Expected undefined to be defined.
    Error: Expected undefined to be defined.
        at Object.<anonymous> (/home/oleg/dev/hub/test/fed/api.scenerio.js:346:41)
    Expected false to be truthy.
    Error: Expected false to be truthy.
        at Object.<anonymous> (/home/oleg/dev/hub/test/fed/api.scenerio.js:350:53)


    Expected undefined to be defined.
    Error: Expected undefined to be defined.
        at Object.<anonymous> (/home/oleg/dev/hub/test/fed/api.scenerio.js:346:41)


    Expected false to be truthy.
    Error: Expected false to be truthy.
        at Object.<anonymous> (/home/oleg/dev/hub/test/fed/api.scenerio.js:365:53)


    Expected undefined to be defined.
    Error: Expected undefined to be defined.
        at Object.<anonymous> (/home/oleg/dev/hub/test/fed/api.scenerio.js:362:41)


    Expected undefined to be defined.
    Error: Expected undefined to be defined.
        at Object.<anonymous> (/home/oleg/dev/hub/test/fed/api.scenerio.js:362:41)

Source: (StackOverflow)

Masonry Events: Call event after imagesLoaded and layoutComplete

So here's what I'm trying to do. I have a grid with a lot of images, so I'm using the imagesLoaded library along with masonry.

Here's my CSS:

.grid {
    opacity:0;
}

And HTML:

<div class="grid">
    <div class="grid-sizer"></div>
    <div class="gutter-sizer"></div>
    <div class="item">image</div>
    <div class="item">image</div>
    <div class="item">image</div>
</div>

And here's my JS:

var $container = $('.grid');
// initialize Masonry after all images have loaded  
$container.imagesLoaded( function() {
    $container.masonry({
        columnWidth: '.grid-sizer',
        itemSelector: '.item',
        gutter: '.gutter-sizer'
    });
    $container.masonry('on', 'layoutComplete', function(){
        console.log('got here');
        $container.animate({'opacity':1});
    });
});

My goal is to have the grid hidden until all images are load and the layout is complete, and then fade it in. For some reason in my code above, it's never getting into the on layoutComplete block.

If I move that block outside of imagesLoaded, $container.masonry is undefined that point.

Any ideas?

FIDDLE HERE

If you change the grid opacity to 1 you can see everything is getting laid out fine. Just trying to figure out how to get the layoutComplete to call to set the opacity to 1.


Source: (StackOverflow)

Advertisements

imagesloaded from image array

I am using imagesloaded and jquery, see the code below.

var img = new Image();

img.src = 'abc.jpg',
          'def.jpg';

var imgLoad = imagesLoaded(img);

imgLoad.on( 'progress', function( instance, image ) {
  var result = image.isLoaded ? 'loaded' : 'broken';
  console.log( 'image is ' + result + ' for ' + image.img.src );
});

It only checks abc.jpg (the first image specified in the source). The second image is not being checked by the code. How can I check all images in img.src?


Source: (StackOverflow)

How to load a large amount of images through jQuery ImagesLoaded

I have a page that loads approx 150+ images into a page. The structure for the image is this:

HTML CODE

<table class="form-table">
  <input type="hidden" name="bgtype" id="bgtype" value="pattern"/>
  <tr class="wpbp-field-patternbg">
    <th style="width:20%"><label for="patternbg">Pattern</label></th>
    <td><div id="wpbp-pattern-select">
        <div class="description">Select a pattern you would like to be applied as the background. Click on a pattern to select it.<br>
        </div>
        <input class="radio" type="radio" name="patternbg" id="patternbg2" value="45degreee_fabric.png"  checked='checked'>
        <label for="patternbg2" class="is-loading"><a class="pattern_preview" data-img="45degreee_fabric.png" data-content="45degreee fabric"><img src="45degreee_fabric.png" alt="" class="wpbp-pattern-img "/></a></label>
        <input class="radio" type="radio" name="patternbg" id="patternbg3" value="patterns/60degree_gray.png" >
        <label for="patternbg3" class="is-loading"><a class="pattern_preview" data-img="60degree_gray.png" data-content="60degree gray"><img src="60degree_gray.png" alt="" class="wpbp-pattern-img "/></a></label>
        <input class="radio" type="radio" name="patternbg" id="patternbg4" value="always_grey.png" >
        <label for="patternbg4" class="is-loading"><a class="pattern_preview" data-img="always_grey.png" data-content="always grey"><img src="always_grey.png" alt="" class="wpbp-pattern-img "/></a></label>
        </div></td>
  </tr>
</table>

( I have removed the full path to the images to make the code above at a minimum )

CSS CODE

#wpbp-pattern-select.is-loading {
  background-image: url('../images/loading.gif');

}
#wpbp-pattern-select .is-loading img {
  opacity: 0;
}

JQUERY

var $container = $('#wpbp-pattern-select');
$imgs = $container.find('img'),

// use ImagesLoaded
$container.imagesLoaded()
  .progress( onProgress )
// reset progress counter
imageCount = $container.find('img').length;
console.log( imageCount + ' properly loaded images' );

// triggered after each item is loaded
function onProgress( imgLoad, image ) {
  var $item = $container.find('img');
  $item.removeClass('is-loading');
}

What I want to achieve is to have a preloading spinner (.is-loading) display on each individual image until that certain image has been loaded. When it is finished loading the spinner will remove displaying the original image.

I have tried playing around with the jQuery imagesLoaded library to get this to work but I can't get it right. Can this be done?

Any help would be greatly appreciated, thanks


Source: (StackOverflow)

How do I get a script to load before masonry?

I'm quite new to javascript so bear with me if this is described quite horribly... I'm sure there's a simple solution if someone could take the time to check this code for me:

http://nang-nang.net/masonry/index.html

^My test site

I'm trying to use Masonry but unloaded images are causing elements to overlap. There is a solution provided (in the Masonry appendix page) called ImagesLoaded, which I tried, but I couldn't get it to work. Then I thought, ImagesLoaded might not be working because the image that is causing the problem is being generated by another javascript...

I'm using a script that pulls the latest image from your tumblr blog. It's my latest tumblr image that isn't loading before Masonry arranges my elements. So the element after the tumblr element always appears on top of it. (I can't set the height of that image because it always varies.)

I guess my question is; how to do I get the tumblr script to load my latest tumblr image before Masonry can arrange my elements?


Source: (StackOverflow)

Bad masonry element: null - using wordpress

I am writing a wordpress plugin in php (sorry, dont know very much about java script). In that plugin I output pictures with a little text and want to do that with masonry.

When I initialzie masonry in HTML, it seems to work, but the pictures overlap:

<div id="container" class="js-masonry"  data-masonry-options='{ "columnWidth": 200, "itemSelector": ".item" }'>

Therefore I am trying to use "Imagesloaded" (by the same developer?).

But as I see it, before I can use ImagesLoaded I need to get Masonry up and running with javascript. When I initialize Masonry in my plugin_scripts.js I get an error on the frontend:

plugin_scripts.js:

jQuery(function() {

alert("hallo");
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
  // options
  columnWidth: 200,
  itemSelector: '.item'
});

});

Console Error in Frontend:

Bad masonry element: null 
masonry.min.js?ver=3.1.2:1
q masonry.min.js?ver=3.1.2:1
d masonry.min.js?ver=3.1.2:1
(anonymous function) schnoogle_scripts_frontend.js?ver=3.9.2:10
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
n.extend.ready jquery.js?ver=1.11.0:2
K jquery.js?ver=1.11.0:2

Can you help?


Source: (StackOverflow)

ImagesLoaded does not work with Firefox without setTimeout

Any ideas why I require a timeout of at least 300ms for imagesLoaded to work on Firefox? If I set it any less, the imagesLoaded event fires immediately before the image has loaded. I am using the latest version 3.1.x.

<html>
    <script src="bower_components/jquery/jquery.min.js"></script>
    <script src="bower_components/imagesloaded/imagesloaded.pkgd.js"></script>
<head>
</head>
<body>
    <div id=myimage><img style="height:100px" src="http://www.worldcarwallpapers.com/wp-content/uploads/2013/07/new-2014-audi-r8-wallpaper.jpg"/></div>
    <script>
        $(document).ready(function(){
            setTimeout(function(){
                var elem = $("#myimage");
                elem.imagesLoaded(function(){
                    alert("ready!!")
                });
            }, 100)
        })
    </script>
</body>
</html>

Source: (StackOverflow)

Update jquery deferred object element dynamically

I am checking if image is loaded of not using imagesloaded library and if anytime image is not able to load then I am replacing "src" with "data-src". Basically my html structure is as below.

<img id="pics-image-0-1" src="URL1" data-src="URL2" owidth="137" style="visibility: visible; margin-left: -4px; width: 137px;">
<img id="pics-image-0-2" src="URL1" data-src="URL2" owidth="137" style="visibility: visible; margin-left: -4px; width: 137px;">

I have used imagesloaded as below

jQuery("img[id^='pics-image-0").imagesLoaded()
   .progress(function (instance, image) {
        var imgId = image.img.id;
        if (image.isLoaded) {
            //display the image.
        }  else{
            // replace src with data-src
        }
    });

In above code I am replacing src with data-src when I know that URL1 is broken.

But sometimes due to heavy load on sever if URL1 is being served very slow then I want that if URL1 is not able to load in 20 seconds then replace src with data-src.

To do this I am thinking of an independent function which will do it after 20 second. But my question is will it be good approach? Is it fine to modify deferred object at runtime.

I tried to write wrapper on imagesloaded.js to meet my requirement but no luck.

I also tried with https://github.com/darsain/imagesloaded (different version) but not working as expected.

Can anyone suggest how to address above issue? Is replacing url using independent function is fine?


Source: (StackOverflow)

How to append images with the correct height, without overlap using masonry and imagesloaded plugin?

Presently on my site I am using imagesloaded to do masonry once all images have loaded for all items. But this is causing a cascade of items (item divs arranged one below the other) until all the images are loaded and then masonry happens.

$(document).ready(function(){do_masonry();});

function do_masonry(){
var $container = $('#content');
var gutter = 10;
var min_width = 200;
$container.imagesLoaded( function(){
   $container.masonry({
        itemSelector : '.item',
        gutterWidth: gutter,
        isAnimated: true,
        columnWidth: function( containerWidth ) {
           //some calculations to set each item div's width
            return item_width;
          }
    });

I would like to do masonry immediately on document ready and then append images as they are loaded into each div that forms an item but when I try this, the result looks ugly with divs overlapping vertically in masonry layout.

Am wondering how to accomplish lazy loading the images with correct heights to each divs without overlapping using masonry append?


Source: (StackOverflow)

Isotope not working with imagesLoaded?

I'm using jQuery Isotope to create a horizontal layout, aligning DIVs with 100% height next to each other and center images inside each DIV vertically. So for, I'm calling Isotope like this and everything works fine in Chrome (locally):

$(function(){
    var $container = $('#container');
    $container.isotope({
        itemSelector : '.itemwrap',
        layoutMode: 'horizontal',
        horizontal: {
            verticalAlignment: 0.5
        }
    });
});

As the images take time to load, they tend to mess up the Isotope layout, so I'm trying to work with the imagesLoaded fix: http://isotope.metafizzy.co/appendix.html

I implemented this fix like this:

$(function(){
    var $container = $('#container');
    $container.imagesLoaded( function(){
        $container.isotope({
            itemSelector : '.itemwrap',
            layoutMode: 'horizontal',
            horizontal: {
                verticalAlignment: 0.5
            }
        });
    });
});

With this imagesLoaded, the Isotope does not load at all anymore. Removing imagesLoaded, Isotope kicks in again (but with the messed up layouts). Does anyone know, where the mistake lies?

Thanks!


Source: (StackOverflow)

Why am I getting "cannot read property 'length' of null" in my imagesLoaded.js while using masonry

I'm trying to replicate the tympanus demo using masonry and animonscroll.js. the only difference is I'm using div cards with images inside them instead of just images.

Here is the working tympanus demo http://jsfiddle.net/Sfmv9/19/light/

And here is my code: http://codepen.io/anon/pen/CotJv.

For whatever reason this works in codepen, but I am suffering from the following issues on my local machine.

  1. The cards are not animating on scroll

  2. Once in a while the cards load on top of one another (which I'm guessing means imagesLoaded is not doing it's job)

  3. I am receiving:

    'Typeerror: Cannot read property 'length' of null imagesloaded.js'

This is the third question I have posted about this issue in the past two months and still cannot figure out why I'm getting this error and how to fix it. I am posting this again (with more specific information) to see if anyone may be able to help.

The error appears to be in this function in imagesloaded.js

// turn element or nodeList into an array
function makeArray( obj ) {
  var ary = [];
  if ( isArray( obj ) ) {
    // use object if already an array
    ary = obj;
  } else if ( typeof obj.length === 'number' ) {
    // convert nodeList to array
    for ( var i=0, len = obj.length; i < len; i++ ) {
      ary.push( obj[i] );
    }
  } else {
    // array of single index
    ary.push( obj );
  }
  return ary;
}

Per the advice of someone in my previous post, I tried changing obj.length == 'number' to:

if ( obj && typeof obj.length === 'number' )

I've also tried changing my container class to a container id in AnimOnScroll.js among many other attempted solutions, but the error remains. Because I am a little shaky with js, I am not able to trace how AnimOnScroll, ImagesLoaded and Masonry all connect with eachother so I don't know if the problem is in fact ImagesLoaded.js or in AnimOnScroll.js.

What confuses me more than anything is why this would work in codepen but not on my local machine.

And if it helps, here are the links to my previous questions.

Why are my divs not animating on scroll?

What could cause animonscroll.js to work on codepen but not on my local machine?

Why am I getting 'Cannot read property 'length' of null' in this js code?


Source: (StackOverflow)

Split divs with class from html to be used by script

I am trying to build my own 'infinite scroll' so I have more control than using a plugin.

I currently have the below:

$(window).scroll(function(){
      if  ($(window).scrollTop() == $(document).height() - $(window).height()){
         loadNew();
      }
}); 

function loadNew(){  
    var next = $('a.next').attr('href');

    $.ajax({
        url: next,
        success: function(html){

            ** GET ALL '.grid-item' TO USE BELOW**

            var $newElems = $( **ALL .grid-item** ).css({ opacity: 0 });
            $newElems.imagesLoaded(function(){
                $newElems.animate({ opacity: 1 });
                $container.masonry( 'appended', $newElems, true );
            });
        }
    });
    return false;
}

This is so far triggering when the user scrolls to the bottom of the page, its then getting the 'next' URL from the pagination and returning the full HTML of the page in the success call.

As you can see in my code, I want to get all divs with the class '.grid-item' to be used by the code below.

I am really struggling to get the '.grid-item' divs seperated to be used.

Is anyone able to explain how I can do this?


Source: (StackOverflow)

jQuery Isotope 2.0 multiple instances on the same page and Images Loaded integration

I've been working with Isotope 2.0 jQuery plugin. Reviewing old examples I've found that many options have changed (initialization and so on...). I've found only one working example which works with 2.0 version:

    $(document).ready(function() {(function ($) {
        var $container = $('#posts'),
            isotope = function () {
                $container.isotope({
                    itemSelector: '.item',
                });
            };
        isotope();
        $(window).on('debouncedresize', isotope);
    }(jQuery));
});

Currently I've two questions: 1). How to integrate this script with Images Loaded plugin. Example from doc won't work because it differs from my init script. 2). I've several div blocks on the site and I'd use them with Isotope independently, in other words the init method should consist from one basic script where I could list available containers and that they would you their own independent filter.

How it could be solved? I've seen similar answer but it works only with 1.5.x version


Source: (StackOverflow)

Combining jQuery code - ImagesLoaded + Shuffle.js

My goal is to put the setupSorting function inside of the ImageLoad function. They work when separated (here), but sorting fails when combined (here).

This:

      $(document).ready (function(){
            /* reshuffle when user clicks a filter item */
            $('.filter-tags a').click(function (e) {
                e.preventDefault();

                // set active class
                $('.filter-tags a').removeClass('active');
                $(this).addClass('active');

                // get group name from clicked item
                var groupName = $(this).attr('data-group');

                // reshuffle grid
                $grid.shuffle('shuffle', groupName );
            });  

Needs to go inside of this:

var ImageLoad = (function( $, imagesLoaded ) {

  var $shuffle = $('.masonry-gallery'),
      $imgs = $shuffle.find('img'),
      $loader = $('#loader'),
      sizer = document.getElementById('#shuffle-sizer'),
      imgLoad,

  init = function() {

    // Create a new imagesLoaded instance
    imgLoad = new imagesLoaded( $imgs.get() );

    // Listen for when all images are done
    // will be executed even if some images fail
    imgLoad.on( 'always', onAllImagesFinished );
  },

  onAllImagesFinished = function( instance ) {

    if ( window.console && window.console.log ) {
      console.log( instance );
    }

    // Hide loader
    $loader.addClass('hidden');

    // Adds visibility: visible;
    $shuffle.addClass('images-loaded');

    // Initialize shuffle
    $shuffle.shuffle({
      sizer: sizer,
      itemSelector: '.gallery-photo'
    });
  };

  return {
    init: init
  };
}( jQuery, window.imagesLoaded ));

$(document).ready(function() {
  ImageLoad.init();
});  

With the ultimate goal of being like this page, only with sorting: http://vestride.github.io/Shuffle/images/


Source: (StackOverflow)

functions are undefind inside react object

i am struggling for 2 days on this, i am trying to call imagesLoaded function (which is imported properly in the scripts area), but when calling it from inside a component prop, i get an error that it is indefined.

my code:

    var MasonryContainer = React.createClass({

    imagesLoadedFunc: function() { //omitting the imageloaded call here fix everything
                  this.imagesloaded();
                  this.refs[reference].getDOMNode().imagesLoaded(function() {
                   this.masonry.layout()
                     });

    },
    componentDidMount: function() {
                if (!isBrowser) return;
                this.initializeMasonry();
                this.performLayout();
                this.imagesLoadedFunc();
            },

    componentDidUpdate: function() {
                if (!isBrowser) return;

                this.performLayout();
                this.imagesLoadedFunc(this);
            },

            domChildren: [],

    initializeMasonry: function(force) {
        if (!this.masonry || force) {
            this.masonry = new Masonry(this.refs[reference].getDOMNode(), options);
            this.domChildren = this.getNewDomChildren();
        }
    },

    getNewDomChildren: function () {
        var node = this.refs[reference].getDOMNode();
        var children = options.itemSelector ? node.querySelectorAll(options.itemSelector) : node.children;

        return Array.prototype.slice.call(children);
    },

    diffDomChildren: function() {
        var oldChildren = this.domChildren;
        var newChildren = this.getNewDomChildren();
        var removed = oldChildren.filter(function(oldChild) {
            return !~newChildren.indexOf(oldChild);
        });

        var added = newChildren.filter(function(newChild) {
            return !~oldChildren.indexOf(newChild);
        });

        var moved = [];

        if (removed.length === 0) {
            moved = oldChildren.filter(function(child, index) {
                return index !== newChildren.indexOf(child);
            });
        }
        this.domChildren = newChildren;
        return {
            old: oldChildren,
            'new': newChildren, // fix for ie8
            removed: removed,
            added: added,
            moved: moved
        };
    },

    performLayout: function() {
        var diff = this.diffDomChildren();

        if (diff.removed.length > 0) {
            this.masonry.remove(diff.removed);
            this.masonry.reloadItems();
        }

        if (diff.added.length > 0) {
            this.masonry.appended(diff.added);
        }

        if (diff.moved.length > 0) {
            this.masonry.reloadItems();
        }

        this.masonry.layout();
    },


    componentWillReceiveProps: function() {
        setTimeout(function() {
            this.masonry.reloadItems();
            this.forceUpdate();
        }.bind(this), 0);
    },

    render: function () {
        return (
            <div className="content" ref="masonryContainer">
                <div className='Item'>
                    <img src="/img/gallery/3.jpg"></img>
                </div>
                <div className='Item'>
                    <img src="/img/gallery/11.jpg"></img>
                </div>
                <div className='Item'>
                    <img src="/img/gallery/12.jpg"></img>
                </div>
                <div className='Item'>
                    <img src="/img/gallery/12.jpg"></img>
                </div>
                <img src="/img/gallery/4.jpg"></img>
                <img src="/img/gallery/5.jpg"></img>
                <img src="/img/gallery/6.jpg"></img>
                <img src="/img/gallery/7.jpg"></img>
                <img src="/img/gallery/8.jpg"></img>
                <img src="/img/gallery/9.jpg"></img>
            </div>
        );
    }
});
    React.render(
    <MasonryContainer/>, document.getElementById('reactbody')
    )
</script>

if i call the imageloaded constructor outside of the react component, it is working. any idea what i am missing?

thanks!


Source: (StackOverflow)