Wydzielenie kodu jQuery obsługującego automatyczne ładowanie obrazków do biblioteki...
[redakcja.git] / project / static / js / jquery.lazyload.js
1 (function($) {
2     jQuery.fn.lazyload = function(pattern, options) {
3         var settings = {
4             threshold: 0,
5             scrollThreshold: 300,
6             placeholder: 'loading...',
7             checkInterval: 2000
8         };
9         
10         if (options) {
11             $.extend(settings, options);
12         }
13         
14         var container = this;
15         container.data('lastScroll', -10000);
16         
17         function aboveViewport(container, element, threshold) {
18             return $(container).offset().top >= $(element).offset().top + $(element).height() + threshold;
19         }
20         
21         function belowViewport(container, element, threshold) {
22             return $(container).offset().top + $(container).height() + threshold <= $(element).offset().top;
23         }
24         
25         function checkScroll() {
26             if (Math.abs(container.scrollTop() - container.data('lastScroll')) > settings.scrollThreshold) {
27                 container.data('lastScroll', container.scrollTop());
28                 
29                 $(pattern, container).each(function() {
30                     if (aboveViewport(container, this, settings.threshold)
31                         || belowViewport(container, this, settings.threshold)) {
32                         $(this).html(settings.placeholder);
33                     } else {
34                         $(this).html('<img src="' + $(this).attr('src') + '" width="' + $(this).width() + '" />');
35                     }
36                 })
37             }
38             setTimeout(checkScroll, settings.checkInterval);
39         }
40         
41         checkScroll();
42     };
43 })(jQuery);