3

I have a page where a search field is placed in the header. This input uses the autofocus attribute to automatically place the focus into the field so that users can start searching right away:

<html>
  <head><title>autofocus issue</title></head>
  <body>
    <header>
      <form method="post">
        <input name="search" autofocus />
      </form>
    </header>
    <article>
      <p>Lots of contents here, so that the next link
         can only be reached by scrolling down ...</p>
      <a href="http://link.to/some/page">Go somewhere</a>
    </article>
  </body>
</html>

While this works fine there is a problem when going forth and back in history. If the user scrolls down my page and clicks on a link and then goes back again (using browser history), my original page scrolls to the top where the search input is located.

This is a usability flaw because the scroll position shouldn't change when going back in history. How do I avoid this?

jor
  • 2,058
  • 2
  • 26
  • 46

1 Answers1

1

Instead of using the HTML autofocus attribute you would want to check with JS if the user navigated to your page via the back button. Then only if they did NOT, you would call searchField.focus().

The problem is, I see no direct way to detect if the user clicked the “back” button. You could however, try getting the scroll position, and call .focus() only if scrolled 0px:

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
if (scrollTop === 0) {
    searchField.focus();
}
Community
  • 1
  • 1
Web_Designer
  • 72,308
  • 93
  • 206
  • 262