Skip to content

Instantly share code, notes, and snippets.

@gabelloyd
Last active April 3, 2017 17:03
Show Gist options
  • Save gabelloyd/f4e338731c0fb73bcad2e4a2d9872716 to your computer and use it in GitHub Desktop.
Save gabelloyd/f4e338731c0fb73bcad2e4a2d9872716 to your computer and use it in GitHub Desktop.
Add or remove styling classes to images depending if they load or not. Uses desandro's imagesloaded.js
/*
* Support Images loading or not
* if there are broken images, we hide the broken image icon with a "lazy" class
* add img-enhance-ui class to all images in theme.
* http://codepen.io/ire/pen/xVxgeo
* using "broken-3" styles
*
* If the images load, we will add class "appear" so they will fade in nicely.
* this is not optimized to be hooked into the scrolling behavior, just page load
* http://codepen.io/desandro/pen/bIFyl
* http://imagesloaded.desandro.com/
*
* @since 3.5.1.3
* @author Gabe Lloyd
*/
jQuery(document).ready(function($) {
var $container = $('#content');
var $progress = $('progress');
// Check for IE support
var supportsProgress = $progress[0] &&
// IE does not support progress
$progress[0].toString().indexOf('Unknown') === -1;
// use ImagesLoaded
$container.imagesLoaded()
.progress(onProgress)
// triggered after each item is loaded
function onProgress( imgLoad, image ) {
// change class if the image is loaded or broken
var $item = $( image.img );
// Make sure we appear our images
$item.removeClass('lazy').addClass('appear');
// Change the class for broken images
if ( !image.isLoaded ) {
$item.removeClass('appear').addClass('hidden'); // using hidden here because we use Bootstrap. Apply any class here that will remove from DOM or hide element
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment