Pangloss Pangloss - 5 months ago 18
CSS Question

Reset checkbox checked state go back from history

In the following example, I use checkbox for making a pure CSS dropdown navigation, also available in this jsFiddle example.

Open that fiddle, click "Menu", click "Link 1", and click the "Back" button on the browser toolbar, as you can see the checkbox remains checked, so the navigation is still open.

My question is - would it be possible to reset that checkbox to unchecked automatically when going back from the browser history? Any suggestions please? Do I need to Javascript/jQuery?

HTML

<label for="m">Menu</label>
<input id="m" type="checkbox">
<nav id="n">
<ul>
<li><a href="//example.com">Link 1</a></li>
</ul>
</nav>


CSS

#n {
display: none;
}
#m:checked ~ #n {
display: block;
}

Answer

No need for JS or CSS, just add autocomplete="off" to the checkbox. This will prevent the browser from caching the 'checked' status.

Example: https://jsfiddle.net/6g5u8wkb/

Also, if you have multiple checkboxes, I beleive you can add autocomplete="off" to the form element to apply the effect to all inputs fields.