Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 use 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;
}
like image 440
Stickers Avatar asked Jun 20 '16 22:06

Stickers


People also ask

Why does the checkbox stay checked when reloading the page?

It means that the checkbox should be empty based on what you are trying to do. However if you were to click the box and reload the page your checked will be true however your input will not be checked. So the issue lies in how you are setting your DOM element to be in a checked state.

How do I keep a checkbox checked in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.


1 Answers

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.

like image 192
Dryden Long Avatar answered Sep 17 '22 13:09

Dryden Long