0

I have some jQuery code to move a div to a later location in the flow when the window size is below 767px. All works fine.

I also have some jQuery code to scroll past the main navigation down to the main content after the page loads, again if the device is < 767px.

The scrollTop function works fine. The detach() + insertAfter() function works fine.

But

On the single page that the insertAfter() code affects, the scrollTop code scrolls to the wrong area. It seems to be scrolling to where the anchor was before the elements were moved.

Any ideas? The page is live at http://northqueensviewhomes.com/community (remember you will have to shrink your browser window to see any of these behaviors, and you will have to reload your small window to see the scroll function).

Here's the two functions and their invocations…

function rearrangeHelpfulLinks() {
   var $theLinks = $('#quicklinks.rc.well');
   if (($theLinks).length) {
      if ($(window).width() <= 767) {
         $theLinks.detach().insertAfter('.core-copy');
      } else {
         $theLinks.detach().insertAfter('#main-nav');
      }
   }
}


function scrollOnSmallScreen() {
   if ($(window).width() <= 767) {
      $('html, body').animate({
         scrollTop: ($('#main').offset().top - 13)
      }, 3210, 'easeInOutExpo');
   }
}

and the insertAfter() routine is invoked on window resize…

$(window).resize(function() {
   rearrangeHelpfulLinks();
});

…and the scroll function is called on page load (for completeness' sake, simply…)

   scrollOnSmallScreen();

Not sure if you need anything further to help me (again!), but I would love to get the scrolling to the right location, which is simply to the anchor, #main.

All help appreciated.

dashard
  • 877
  • 1
  • 10
  • 17
  • try to call `scrollOnSmallScreen();` using `setTimeout(scrollOnSmallScreen,0);` also it is good to add somewhere `$(window).scroll(function() {$('html body').stop();});` because it is very annoing that i should wait animation end if i want to scroll. – zb' Apr 28 '13 at 00:23
  • setTimeout worked perfectly, thanks. Not sure why I didn't think about it. As for the stop() I'm not sure where to invoke it. Anywhere I place it it kills the autoscroll. – dashard Apr 29 '13 at 03:09
  • you should place `$(window).scroll(function() {$('html body').stop();});` to the script which runs ofter jquery load (to main scope). – zb' Apr 29 '13 at 03:40
  • according to this: http://stackoverflow.com/questions/15435338/animate-scrolltop-fires-scroll-event the scrollTop chages fires events on scroll :( and solution didn't work for me... – zb' Apr 29 '13 at 04:16
  • http://jsfiddle.net/oceog/6a2F2/ this how I acheived the goal :) – zb' Apr 29 '13 at 04:30

1 Answers1

0

Call scrollOnSmallScreen(); using

setTimeout(scrollOnSmallScreen,0);

it will run the autoscroll after your tread and DOM changing thread run.

zb'
  • 8,071
  • 4
  • 41
  • 68