Scrolling a page using location.hash in Safari

I have a forum page that displays a tree view of the posts below the currently selected post. When you click on a message in the tree, the new message text is loaded into a div at the top of the page using AJAX, and then the following code is run:

window.location.hash = "page_top"; 

Of course, "page_top" is a binding element at the top of the page, so the newly loaded message body scrolls to the window.

This works great in all browsers except Safari. In Safari (tested on PC and iPhone), it only works the first time location.hash is set. If you install it again, the page will not scroll.

The end result is that the newly loaded message body does not scroll to the view in Safari, and you need to scroll back to the top of the page every time you select a new message from the tree.

Why don't Safari like it, and is there anything I can do to fix it?

Edit:

I assume this is due to an error you might find in Googling about location.hash and Safari. Safari seems to have had an error where, if you set the hash to the same value twice, this will reload the page. I assume that when they fixed this error, they corrected it too carefully and stopped doing anything when you again set the hash with the same value.

http://www.howtocreate.co.uk/safari/locationHashBug.html

+3
source share
4 answers

Answering my question. Gumbo was on the right track, but not quite there.

Safari doesn't like when location.hash is set to null. Instead, you need to set it to the actual binding value.

So, at the top of the page, I have:

 <div><a href="page_top"></a></div> <div><a href="page_topnot"></a></div> 

I found that I needed divs around anchors, otherwise Safari would scroll to unpredictable parts of the page, not anchors.

Then to scroll to the top of the page I need to do:

 window.location.hash = "page_topnot"; window.location.hash = "page_top"; 

In doing so, Safari will scroll to the top of the page each time.

+1
source

You could reset first:

 window.location.hash = ""; window.location.hash = "page_top"; 
+3
source

I needed to add:

 <div><a name="page_top"></a></div> <div><a name="page_topnot"></a></div> 

Using "name" instead of "a href". It works great!

+2
source

I had the same problem as you did, and this solution worked - the only thing I noticed was that in IE I could hear two clicks. So, I made your version and just added one anchor, and it worked (i.e. call twice, the first time, the nonexistent anchor, the second time the real one)

To the beginning, my anchor:

 (tag a)name="top" id="top"(end of tag a) 

There are two calls inside javascript:

 window.location.hash ="topnot"; window.location.hash ="top"; 

Thanks for your help!

0
source

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


All Articles