ressio / lazy-load-xt

Lazy load XT is a jQuery plugin for images, videos and other media
http://ress.io/lazy-load-xt-jquery/
MIT License
1.36k stars 245 forks source link

Background-img with Img Tags #17

Open explorador opened 9 years ago

explorador commented 9 years ago

If I use img tags with the background-img addson (I needed to use both) I get an undefined error, this is what I did to fix it:

(This is the background-img addson code)

/*! Lazy Load XT v1.0.5 2014-06-05

(function ($) { var options = $.lazyLoadXT, bgAttr = options.bgAttr || 'data-bg';

options.selector += ',[' + bgAttr + ']';

$(document).on('lazyshow', function (e) {
    var $this = $(e.target);

    //If this element has this bgAttr attibute, then...
    if ($this.is("["+bgAttr+"]")) {
        $this
            .css('background-image', "url('" + $this.attr(bgAttr) + "')")
            .removeAttr(bgAttr)
            .removeClass('lazy-hidden'); //I had to add this cause I was using the css fade-in css code and the opacity was set to 0.           
    }        

});

})(window.jQuery || window.Zepto || window.$);

DoomDesign commented 9 years ago

Thank you @explorador ! @ressio please include this in the addon :)

nguyenj commented 9 years ago

@ressio please include this in the dist as well :)

262media commented 9 years ago

This is still an issue and even that i know the fix every time i make a new deploy it gets overwritten

acoard commented 8 years ago

Hey all. I made a few tweaks. Now the background image is only shown once the image has been loaded.

(function ($) {
 var options = $.lazyLoadXT,
  bgAttr = options.bgAttr || 'data-bg';

  options.selector += ',[' + bgAttr + ']';

  $(document).on('lazyshow', function (e) {
      var $this = $(e.target);
      //If this element has this bgAttr attibute, then...
      if ($this.is("["+bgAttr+"]")) {

        $('<img/>').attr('src', $this.attr(bgAttr) ).load(function(){
         //We load the image into an <img> and then immediately delete it once the image is loaded
        //Now that it's cached, when we set the bg-image it'll be instant.
          $(this).remove();
          $this
              .css('background-image', "url('" + $this.attr(bgAttr) + "')")
              .removeAttr(bgAttr)
              .removeClass('lazy-hidden'); //I had to add this cause I was using the css fade-in css code and the opacity was set to 0.           
        })
      }        

  });
})(window.jQuery || window.Zepto || window.$);
Daijobou commented 8 years ago

thank you. :+1: