↓ Twitter is updated more often, so read it! ↓

Select/option dropdowns versus the back button: a workaround

When using select elements on a page (also known as drop downs) as a navigation item, it’s possible that the selected option will persist if the user use’s the browser’s back button.

Consider this workflow:

  1. User clicks on dropdown and selects an item.
  2. Javascript executes, doing something like “window.location = document.forms[0].selectElement.value”
  3. Browser goes to next page.
  4. User clicks back button, browser goes to previous page.
  5. User is confused because the dropdown item contains what they just selected, not what was there when the page loaded.

This is an unfortunate bug/feature in Firefox and Chrome. It actually behaves as one would think in IE and Safari.

The reason is because of Gecko and Webkit’s bfcache, a feature which caches forward and backward pages so that they do not have to be reevaluated in order to be rerendered to the screen. IE reevaluates to rerender. I’m not sure why Safari behaves.

The trick is to use window.onpageshow and window.onload to handle the value of the sortby.

You’ll want something like this:

window.onload = “restoreSelect();”;
window.onpageshow = “restoreSelect();”;

or whatever the equivalent is in your favorite Javascript framework.

Don’t store the value in cookies. It’ll create problems if a user is using multiple tabs. The value I needed is always in the URL, so I could use that for this particular instance.

This trick works for me in Firefox, Chrome, Safari, and IE. I have not tried it on Opera.

One Comment

  1. Select/option dropdowns versus the back button: a workaround [ The Flow of Consciousness ]:

    [...] Meanderings and punditry by a computer scientist with penchant for journalismeducationand politics From: cad.cx [...]

Leave a comment