Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location.hash = " "; prevent scrolling to the top?

Tags:

in my website i set the url adress using

window.location.hash = 'project_name'; 

but if i want to clean the adress url from any hashes (when i close a project) and i set

window.location.hash = ''; 

it happens the page scrolls up to the top page

there is any way to clean up the url without any side effect?

thanks

like image 461
Francesco Avatar asked Jan 17 '11 15:01

Francesco


People also ask

What does Window location Hash do?

The window. location. hash returns a string that contains a # along with the fragment identifier of the URL. The fragment identifier of the URL starts with a # followed by an identifier that uniquely identifies a section in an HTML document.

How do I know if my browser window is scrolled to the top?

You can check if window. scrollY (the number of pixels the window has scrolled vertically) is equal to 0 . If you want to check if the window has been scrolled to its leftermost, you can check if window. scrollX (the number of pixels the window has scrolled horizontally) is equal to 0 .


2 Answers

There's the onhashchange event, but it cannot be cancelled reliably across browsers to prevent scrolling. The best solution is to record the scroll position before changing the hash location and reset it afterwards. For example, the following code will catch a click on any link ― that doesn't stop propagation ― with a href value of # and prevent the page from scrolling vertically:

document.onclick = function (evt) {     var tgt = (evt && evt.target) || event.srcElement,         scr = document.body.scrollTop;      if (tgt.tagName == "A" && tgt.href.slice(-1) == "#") {         window.location.href = "#";         document.body.scrollTop = scr;                    return false;     } } 

If you're changing the hash through script, you can use the following code:

var scr = document.body.scrollTop; window.location.href = '#'; document.body.scrollTop = scr; 

Either of those methods can be adjusted to avoid scrolling individual elements or scrolling the page horizontally. Note that you can remove the entire hash (including the #) without causing navigation or scrolling in modern browsers by calling the pushState or replaceState functions.

like image 64
Andy E Avatar answered Sep 20 '22 15:09

Andy E


I was having the same problem and came here for an answer. Just found out there is a very easy way:

window.location.hash = ' '; 

Basically you are setting it to '# ', since the space doesn't exist, it doesn't move. When you revisit the page, it also doesn't treat it any differently than just #

like image 45
JustMaier Avatar answered Sep 19 '22 15:09

JustMaier