What event works best for retrieving session storage values

58 views Asked by At

I am trying to use session storage to save the values of the slider on my browser. On page reload I keep getting my default 0.5 being displayed. The script seems fine, I am wondering if using a "change" event is not the best approach.

jsfiddle : https://jsfiddle.net/q8c4d32f/14/

// With JQuery
$("#ex6").slider({
        tooltip: "hide"
});

$("#ex6").on("slide", function(slideEvt) {
    $("#ex6SliderVal").text(slideEvt.value);
  let set = sessionStorage.setItem("slider", slideEvt.value);
});

$("#ex6").on("change", function(changeEvt) {
  let get = sessionStorage.getItem("slider");
});
div{
  margin-top: 15px;
  margin-left: 15px;
}
<link rel="stylesheet" type="text/css"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.css"
      integrity="sha512-SZgE3m1he0aEF3tIxxnz/3mXu/u/wlMNxQSnE0Cni9j/O8Gs+TjM9tm1NX34nRQ7GiLwUEzwuE3Wv2FLz2667w=="
      crossorigin="anonymous" />


<!--Importing Javascript-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
        integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.min.js"
        integrity="sha512-f0VlzJbcEB6KiW8ZVtL+5HWPDyW1+nJEjguZ5IVnSQkvZbwBt2RfCBY0CBO1PsMAqxxrG4Di6TfsCPP3ZRwKpA=="
        crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"></script>
        
<div>
<input id="ex6" type="text" data-slider-min="0.0" data-slider-max="1.0" data-slider-step=".1" data-slider-value="0.5"/>
<span id="ex6CurrentSliderValLabel">Current Slider Value: <span id="ex6SliderVal">0.5</span></span>
</div>

1

There are 1 answers

2
Louys Patrice Bessette On BEST ANSWER

Initialise the slider inside a document ready after having retreived the session storage.

$(document).ready(function(){
  let get = sessionStorage.getItem("slider") || 0.5 // If there is no session storage, use 0.5
  console.log(get);
  
  $("#ex6").slider({
        tooltip: "hide",
        value: get
  });

  $("#ex6SliderVal").text(get);
})

Your Fiddle updated