Window.location.hash - stop reload in chrome

I have the following problem:

$('.gotoservices').click(function(){ $('html,body').scrollTo($("#services"),1000); window.location.hash = "services"; return false; }); 

This code works, but for some reason, the page blinks before scrollTo .

If I delete the line window.location.hash , it works return false; , and the page does not blink / flicker.

I tried e.preventDefault - not working

I'm struggling to find any job.

Greetings

+4
source share
2 answers

In a general sense, you can update the URL using HTML5 history without re-rendering the browser:

 history.pushState(null, null, '#myhash'); 

Of course, you most likely want to have backups for older browsers, and you can only do this after the animation is complete.

So integrated with your code:

 $('.gotoservices').click(function(e){ //Prevent default so the browser doesn't try to do anything e.preventDefault(); var $hash = "#services"; $('html,body').scrollTo($($hash), 1000, function () { //If the browser supports HTML5 history, //use that to update the hash in the URL if (history.pushState) { history.pushState(null, null, $hash); } //Else use the old-fashioned method to do the same thing, //albeit with a flicker of content else { location.hash = $hash; } }); }); 
+1
source

Why don't you just make a function that scrolls specifically to #services? You tell your web browser to go to #services, and then go to #services. There is probably a conflict with this. If you are trying to update the url to have a hash, you probably need

 $(window).bind('hashchange', function(e) { e.preventDefault(); }); 

So that he does not try to "go to the hash."

0
source

Source: https://habr.com/ru/post/1384183/


All Articles