PotatoFro
PotatoFro

Reputation: 6638

Prepend a div without shifting the contents down? Using iScroll

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!

Upvotes: 0

Views: 713

Answers (2)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

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.

Upvotes: 0

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

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.

Upvotes: 1

Related Questions