There is a sorting unit, the sorting is performed on the server. After reloading the page, it is necessary to smoothly scroll to the sorted content.

I hook the anchors #sort_anchor to the url of the buttons, in the header before loading the html hard disk:

window.hashName = window.location.hash; window.location.hash = ''; 

In the template I call

 $(window).load(function () { $('html, body').animate({scrollTop: $(window.hashName).offset().top-50}, 500); return false;}); 

Everything works, smooth scrolling is. But there was an error:

 Uncaught TypeError: Cannot read property 'top' of undefined 

I understand the reason, how to solve I do not know. Prompt pl!

  • Are you sure that $ (window.hashName) is such an element? Try to remove this animation function, if it causes an error and everything works, then this block is not needed - Jurij Jazdanov
  • Your mistake means that there is no element in the DOM - And Rey

2 answers 2

When you receive a hash using the window.location.hash method, you should return #sort_anchor which, as is clear, cannot be a selector. You need to separate it from the received information, for example

  var hash = window.location.hash.split('#'); if(hash != undefined){ window.location.hash = ''; console.log(hash[1]); /* послС ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ ΠΌΠΎΠΆΠ½ΠΎ ΡΠ΄Π΅Π»Π°Ρ‚ΡŒ Π°Π½ΠΈΠΌΠ°Ρ†ΠΈΡŽ*/ /*ΠΊΠΎΠ΄ Π°Π½ΠΈΠΌΠ°Ρ†ΠΈΠΈ*/ } 
  • The code does not work in the console undefined - Vital
  • do you have an anchor in the address bar #sort_anchor? you always have to check the presence of an anchor when performing an animation - Arsen
  • after rebooting n a short time #sort_anchor is there then it executes the script and leaves # - Vital
  • Why do you remove the anchor? in your example, you delete using window.location.hash = ''; - Arsen
  • I delete the anchor, because the server will immediately send to the anchor. - Vital

Thanks Arsen! won! Sample working code:

 window.hashName = window.location.hash; //Π»ΠΎΠΆΠΈΠΌ Π² ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ window.location.hash = ''; //ΠΎΡ‡ΠΈΡ‰Π°Π΅ΠΌ Ρ…ΡΡˆ if( window.hashName[1] != undefined){ //провСряСм $('html, body').animate({scrollTop: $(window.hashName).offset().top-50}, 1500); };