Skip to content

Commit b2a2681

Browse files
committed
Merge pull request #20 from montanajob/setinterval-asneeded
As Needed setInterval
2 parents d17d731 + a947ecc commit b2a2681

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

jquery.inview.js

+21-10
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,35 @@
55
*/
66
(function ($) {
77
var inviewObjects = {}, viewportSize, viewportOffset,
8-
d = document, w = window, documentElement = d.documentElement, expando = $.expando;
8+
d = document, w = window, documentElement = d.documentElement, expando = $.expando, timer;
99

1010
$.event.special.inview = {
1111
add: function(data) {
1212
inviewObjects[data.guid + "-" + this[expando]] = { data: data, $element: $(this) };
13+
14+
// Use setInterval in order to also make sure this captures elements within
15+
// "overflow:scroll" elements or elements that appeared in the dom tree due to
16+
// dom manipulation and reflow
17+
// old: $(window).scroll(checkInView);
18+
//
19+
// By the way, iOS (iPad, iPhone, ...) seems to not execute, or at least delays
20+
// intervals while the user scrolls. Therefore the inview event might fire a bit late there
21+
//
22+
// Don't waste cycles with an interval until we get at least one element that
23+
// has bound to the inview event.
24+
if (!timer && !$.isEmptyObject(inviewObjects)) {
25+
timer = setInterval(checkInView, 250);
26+
}
1327
},
1428

1529
remove: function(data) {
1630
try { delete inviewObjects[data.guid + "-" + this[expando]]; } catch(e) {}
31+
32+
// Clear interval when we no longer have any elements listening
33+
if ($.isEmptyObject(inviewObjects)) {
34+
clearInterval(timer);
35+
timer = null;
36+
}
1737
}
1838
};
1939

@@ -113,13 +133,4 @@
113133
viewportOffset = null;
114134
});
115135
}
116-
117-
// Use setInterval in order to also make sure this captures elements within
118-
// "overflow:scroll" elements or elements that appeared in the dom tree due to
119-
// dom manipulation and reflow
120-
// old: $(window).scroll(checkInView);
121-
//
122-
// By the way, iOS (iPad, iPhone, ...) seems to not execute, or at least delays
123-
// intervals while the user scrolls. Therefore the inview event might fire a bit late there
124-
setInterval(checkInView, 250);
125136
})(jQuery);

0 commit comments

Comments
 (0)