Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 656
Yossi Shasho Avatar asked Feb 08 '16 14:02

Yossi Shasho


1 Answers

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
  };
});
like image 178
Yossi Shasho Avatar answered Oct 20 '22 03:10

Yossi Shasho