0

I have an scroll to element snippet as:

$('html,body').animate({
     scrollTop: $(window.location.hash).offset().top
},1000);  

which is working perfectly but I need to run it after few seconds on getting into the page (with delay), so I used setTimeout() to get this but now the page jumps to the section (hash) without scrolling or prompting any error message.

setTimeout(function(){ 
  $('html,body').animate({
     scrollTop: $(window.location.hash).offset().top
  },1000);   
}, 2000);

can you please let me know what I am doing wrong and why this is not working with delay?!

Behseini
  • 6,066
  • 23
  • 78
  • 125
  • How can it work? window.location.hash returns a part of url after # symbol, scrollTop property requires integer value.. – philosophocat Feb 20 '16 at 07:18
  • @philosophocat, `$(window.location.hash)` - jQuery selector, `hash` here something like `#hash`, so this valid selector for `id` in jQuery. then just get `offset` and `top` property – Grundy Feb 20 '16 at 07:20
  • Can you provide snippet, or jsfiddle that can reproduce your problem? – Grundy Feb 20 '16 at 07:21
  • I do not think that `html,body` is correct. Maybe you meant `html body` (space instead of comma)? – Alexis Wilke Feb 20 '16 at 07:27
  • @AlexisWilke, if this incorrect why this work _without_ timeout? – Grundy Feb 20 '16 at 07:28
  • 1
    @Grundy, if you're right, that's interesting, but unsafe solution: not really good idea to rely on hash without any kind of checking and it can be a key to issue: element just missed. – philosophocat Feb 20 '16 at 07:29
  • Ah. I see why. The answer suggests you use `$(document)` though. http://stackoverflow.com/questions/19303405/difference-between-html-body-animate-and-body-animate – Alexis Wilke Feb 20 '16 at 07:33
  • I just tested and your code worked just fine in SeaMonkey (2.39) and Firefox (44) and Chromium (48)... What browser are you testing with? Except that I put a direct name for the hash instead of using the window hash (where you should already have been scrolled to since that's what the hash is for in the URL...) – Alexis Wilke Feb 20 '16 at 07:38

1 Answers1

0

Try with:

  $('html,body').delay( 2000 ).animate({
     scrollTop: $(window.location.hash).offset().top
  },1000);

Other option is:

window.setTimeout(function(){
      $('html,body').animate({
         scrollTop: $(window.location.hash).offset().top
      },1000);
});
andres.gtz
  • 624
  • 12
  • 22