Save sliding bar position after a page refresh

Viewed 599

I have the following sliding bar and I would like to save the position of the sliding bar that is selected after a page refresh. Currently the position is being saved and only the number/value is not showing correctly. Any ideas on how to make this work?

      var slider = document.getElementById("ran");
      var output = document.getElementById("demo");
      output.innerHTML = slider.value;

      slider.oninput = function() {
          output.innerHTML = this.value;
          save_data();
      };

      function save_data() {
          var input = document.getElementById("ran");
          localStorage.setItem("server", input.value);
      }

      function load_data() {
          var input = document.getElementById("ran");
          input.value = localStorage.getItem("server");
      }

      load_data();
<span id="demo" style="font-weight: bold"></span>
    <form>
      <input type='range' min='0' max="24" step="1" class="slider" value="1" id='ran'/>
    </form>
      

 

2 Answers

You need to set the value for #demo (the <span> which displays the value for the slider) upon calling load_data()

 function load_data() {
     var input = document.getElementById("ran");
     if(localStorage.getItem("server") == null){
         input.value = 1;
     } else {
         input.value = localStorage.getItem("server");
     }
     document.getElementById("demo").innerHTML = slider.value;
 }

One option is to check the local storage for a value upon loading the page. This would eliminate the need for the load_data function and also seems to fix the problem.

var slider = document.getElementById("ran");
var output = document.getElementById("demo");
var server = localStorage.getItem("server");

slider.value = (server) ? server : slider.value;

output.innerHTML = server ? server : slider.value;

slider.oninput = function() {
    output.innerHTML = slider.value;

    localStorage.setItem("server", slider.value);
}
Related