0

I'm doing a DOM manipulation in jQuery, wrapping body in some div elements, so I'm trying to match scroll position from window to div element after this transformations, but somehow it doesn't work.

Here's what I'm doing:

scrollPosition = $(window).scrollTop();
myBody = $("body").detach();
myBody.wrapInner("<div class='someclass'><div class='osm-website'></div></div>");
myWebsite =  myBody.find('.osm-website');
myWebsite.scrollTop(scrollPosition);

and myWebsite scrollTop position is still 0

but if I do this:

myBody.appendTo('html');
$('.osm-website').scrollTop(scrollPosition);

it works.

I have to find a way to scroll it before appending it to dom because this scroll after appending to page causes a brief "flash" in Safari on Mac. I need it to be seemless.

Any help is greatly appreciated

Kwaigon
  • 1
  • 1
  • Okay, I found out that my real problem is that jQuery scrollTop(position) function does not work for elements that are hidden (or not on page) – Kwaigon Mar 19 '15 at 16:15

1 Answers1

0

If you are really appending the content directly to html you could simply use:

// Source: How to get height of entire document with JavaScript?
// http://stackoverflow.com/a/1147768/887539
var body = document.body;
var html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );

$(window).scrollTop(height);

If not you could take your soon to be parent and find the last elements position and add the elements height:

var $parent = $('....');
var $lastChild = $parent.children().last();
var offset = $lastChild.offset();

var scrollPos = offset.top + lastChild.outerHeight(true);

$(window).scrollTop(scrollPos);
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • the thing is, I'm doing css transitions with body. And to do that, I need to wrap the whole body in a div. Because I attach other elements and make them fly around. Now, when I wrap body in a div, scroll position resets, which is fine, I bring it back but during that brief moment whole page "flashes" in Safari, so I'm trying to do the scrolling when body element is detached. – Kwaigon Mar 19 '15 at 15:22
  • thanks for your anwer, I discovered in the meantime that my real problem was that elements with display:none cannot be scrolled to position without showing them on the page. The only way to scroll them is to use "visibility:hidden" then show them after the scroll – Kwaigon Mar 19 '15 at 17:50