Search code examples
htmlcsscheckeduncheckedtoggleswitch

Toggle switch not resetting on reload


Toggle switch retains last status, even on reload

I'm using a toggle switch from W3schools (this one). In the W3schools editor, it goes back to it's established "checked" or "unchecked" position on a reload, but for whatever reason - if I "check" mine, and then reload, it stays checked, or if I uncheck it and then reload, it stays unchecked.

It's important for the project that I'm doing for it to be unchecked on initially loading/any reload/revisit.

I was curious if it was some sort of cache issue since I'm working on it locally on my computer (wordpad for editting the html, firefox to view the file) but I uploaded my work to neocities, and the problem persisted so I assume that means it's the code itself.

<head>
<style>
.selector {
background-color:rgba(255, 255, 0, 0.3);
text-align:center;
border:1px solid gold;
width: 50vw;
max-width:500px;
border-radius:2em;
padding:1em;
font-size:20px;
color:gold;
margin:2em auto auto;
}

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: darkblue;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: gold;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: cornflowerblue;
}


input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}
</style>
</head>
<body>

<div class="selector">Unchecked 
  <label class="switch">
    <input type="checkbox" onclick="hoverFunction()">
     <span class="slider" alt="toggle switch button"></span>
  </label>
 Checked</div>
</body>

How can I fix this?


Solution

  • This is caused by Firefox. If you add the flag autocomplete="off" it should prevent this behavior and you can set the default state with either the "checked" or "unchecked" flag.

    For example:

    <input type="checkbox" onclick="hoverFunction()" autocomplete="off" unchecked>

    Or:

    <input type="checkbox" onclick="hoverFunction()" autocomplete="off" checked>