While trying to tweak some scrolling script to perform "jump to" links on some pages, I noticed that if you have a page with contains a hash tag in the URL, the behavior is different depending on the browsers when you press enter on the address bar, after the page is loaded.
For example, if you load a page with an has in the URL and then scroll away from the target element, I noticed that on Firefox and IE, if you put your cursor on the address bar and press enter, the page will move back to the HTML element having the same id
attribute as the hashtag but the page will not be reloaded.
I also noticed that neither popstate
nor hashchange
events are triggered in such scenario. The scroll
event will most likely be triggered but how can we know this is not the user scrolling but the browser reseting back its position?
Is there any was to detect this type of event in the browsers? Given this is outside the viewport I'm a bit curious. But I have a scenario where I would like to reposition the menu depending is the page is scrolling up or down.
To try to explain what I'm looking for:
- Page with hashtag
#test
and element<div id="test">
- Press F5, the page posisition itself right where the
<div>
is - Scroll up or down
- Go on the address bar and press enter
- ---- Looking for an event to detect the previous action ---
- the page posisition itself
right where the
<div>
is
Example in JSBin (open in Firefox):
http://jsbin.com/rifikereze/1/edit?html,js,output
Output:
http://output.jsbin.com/rifikereze/1#test2
- Open your console in Firefox
- Make sure in the Firefox setting you enable "persistent logs" to keep logs after page reloads
- Press F5 (you should see a console message "reloaded")
- Now try to move the page, put your cursor in the address bar and press enter
- You will see the page does not reload
How can we detect these events (other than scroll events)?
Make sure to use Firefox on Windows if trying to reproduce. It looks like other OSes have other behaviors.