0

I've got a container div with a bunch of scrollable content (for the record I'm using iScroll - if that changes the solution). When I scroll to the top I want to load content above the current scroll position. If I simply prepend the div using jQuery "prepend();" the contents in my scrollable area shift down. Ideally we'd want to keep the current content in the frame and have the scrollable area grow upwards above the content.

Any thoughts?

Thanks!

PotatoFro
  • 6,378
  • 4
  • 20
  • 22

2 Answers2

1

According to the iScroll website, it has a method called scrollToElement:

scrollToElement(el, runtime): scrolls to any element inside the scrolling area. el must be a CSS3 selector. Eg: scrollToElement("#elementID", '400ms')

If you always prepend a fixed amount of divs (e.g. always a single div), I imagine you could use it to scroll to (e.g.) the second element right after you've prepended the new content:

// ... (prepend new content)
myScroll.scrollToElement('#scroller :nth-child(2)', '0ms');

I haven't tried this, so please let us know if this works for you.

  • Thanks for the reply! This method ends up giving us a (very quick) moment of delay before we return to our original scrolling position and seeing as it's possible the user was not exactly lined up with the element used, we also see a tiny shift of the scroll position. – PotatoFro Aug 17 '12 at 23:18
0

After a quick look through iScroll's source, here's what I've found:

  • The current x and y are always available through myScroll.x and myScroll.y.
  • iScroll has an internal function _offset(el), which returns the left and top offset of any given element.

This basically opens up two solutions:

  1. Use _offset(el). While possible, this is inadvisable. The underscore is a convention for marking a function "private", meaning, amongst other things, that it's not part of the official API.

    or

  2. Use the newly added element's height:

    var x = myScroll.x;
    var y = myScroll.y;
    
    // ... (prepend new content)
    y += $('#scroller :first-child').outerHeight();
    
    myScroll.scrollTo(x, y, '0ms');
    

    You may need to pass true to .outerHeight(), which makes it include margins.

Once again, I haven't tested this, so please let us know if it works.