2

I am building a slider in pure HTML / CSS (no JS). It works very well, see the code.

You will need to download it and execute it locally to understand my problem as it is related to the back and forward buttons of the browser.

When clicking on links to navigate, the URL changes to #a1, #a7, #a5, whatever you are doing. The slider scrolls to the appropriate slide correctly. If you manually change the URL, putting #a3 instead of #a7 for example, slider will also scroll correctly.

However, when you go back (or forward), the URL changes from #a3 to #a7 but the content doesn't scroll.

Any idea why? Any idea what I can do to have the scroll on the back action?

2
  • Where are your back/forward buttons? Could you add them, please? Also, do you mind using JavaScript to solve this? Commented Aug 26, 2019 at 11:57
  • I mean the back and forward buttons of the browser. When you navigate in your history. I don't mind a bit of JS, but this looks more like a browser behavior I need to understand than a code problem: when I visit #a3 and then #a5, if I enter #a4 in the URL it will scroll to it, when I navigate backward the URL will change to #a5 but the page will not scroll. Commented Aug 26, 2019 at 12:01

1 Answer 1

3

I asked a Firefox developer and he explained to me why this is the expected behavior, and not a bug.

I misunderstood what was going on with the back action. Quick answer: it doesn't go to the previously selected anchor, it goes where the body scroll was.

Still using the code in the codepen in the question:

  • Remove the overflow-x: scroll from the CSS
  • Click on #a3, then on #a7. The content scroll to #a7
  • Click on the back button of your browser

I thought the browser was scrolling back to #a3. But in fact, it is scrolling to where it was before you clicked on the link. To see it in action:

  • Click on #a5. The URL changes to #a5
  • Move the scroll to have #a3 on the screen
  • Click on #a7. The URL changes to #a7
  • Click on the back button of your browser

The URL changes to #a5 but #a3 is displayed on the screen, as that's where you were before clicking the link.

So, it is the expected behavior according to the whatwg spec.

However, that's not the behavior I want. So, let's go for a dirty hack:

window.onhashchange = function() { window.location.href = window.location.href; }; 

Now, when clicking back, it will force the page to reload locally (no server request) and it will scroll to the element.

Wow, that was an hard one.

Sign up to request clarification or add additional context in comments.

1 Comment

I put #a3 to history then, jump to #a7. With listening on hashchange event, when back clicked, use the hash as id to find the element and scrollintoview.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.