Yossi Shasho February 2016

Ionic: Get the currently visible items in ion-content

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).

Answers


Yossi Shasho February 2016

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
  };
});

Post Status

Asked in February 2016
Viewed 3,283 times
Voted 12
Answered 1 times

Search




Leave an answer