I have a long, scrollable ion-content
area in my app, filled with items using a collection-repeat
.
I need to know which items are visible to the user.
I cannot use the $ionicScrollDelegate.getScrollPosition
to calculate the answer, because each item has a different height (item height is calculated per item).
Ended up calculating the summed heights myself of the elements, and by querying for the translateY
value of the .scroll
element, I can find out which item is in the visible part of the scroll.
It's reinventing the wheel, but works.
When i load the items, i call ScrollManager.setItemHeights(heights)
(heights
is the array of item heights in pixels), and to get the index of the currently visible item: ScrollManager.getVisibleItemIndex()
angular.module("services")
.service('ScrollManager', function() {
var getTranslateY, getVisibleItemIndex, setItemHeights, summedHeights;
summedHeights = null;
setItemHeights = function(heights) {
var height, sum, _i, _len;
summedHeights = [0];
sum = 0;
for (_i = 0, _len = heights.length; _i < _len; _i++) {
height = heights[_i];
sum += height;
summedHeights.push(sum);
}
};
// returns the style translateY of the .scroll element, in pixels
getTranslateY = function() {
return Number(document.querySelector('.scroll').style.transform.match(/,\s*(-?\d+\.?\d*)\s*/)[1]);
};
getVisibleItemIndex = function() {
var i, y;
y = -getTranslateY();
i = 0;
while (summedHeights[i] < y) {
i++;
}
return i;
};
return {
setItemHeights: setItemHeights,
getVisibleItemIndex: getVisibleItemIndex
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With