lokesh / lightbox2

THE original Lightbox script (v2).
http://lokeshdhakar.com/projects/lightbox2/
MIT License
6.19k stars 1.76k forks source link

Provide URL for image not found. #570

Open johnnylee opened 7 years ago

johnnylee commented 7 years ago

I've written a small wrapper for lightbox that takes a few data attributes and sets the parent link to a default image if the thumbnail image isn't found. I thought you might want to include this sort of functionality in the library itself since it's easy to do and may be a common feature.

/** Lightbox wrapper to display a default image when a thumbnail isn't found.

1. Add class `wLightboxWrapper` to img. 
2. Set `src="#"`. 
3. Add `data-src` with desired image URL.
4. Add `data-err-src` with error image URL. 
5. Add `data-err-href` with error image link.

Note that we need to set `src` from the `data-src` otherwise the error event
may be missed.
*/
function wLightboxWrapper($img) {
  var src = $img.data('src');
  $img.attr('src', src);

  $img.on('error', function() {
    var errSrc = $img.data('err-src');
    var errHref = $img.data('err-href');
    $img.attr('src', errSrc);
    $img.parent().attr('href', errHref);
  });
}

$(document).ready(function() {
  $('.wLightboxWrapper').each(function() {
    wLightboxWrapper($(this));
  });
});