Error : cannot call methods on slider prior to initialization attempted to call method 'value'

Rishiraj Fasalkar picture Rishiraj Fasalkar · May 17, 2013 · Viewed 11.7k times · Source

I have written something like below. onclick of div with id "PLUS" I am getting the following error:

cannot call methods on slider prior to initialization attempted to call method 'value'

<div id="PLUS" class="PLUS"></div>
<script>
  $(function() {
    $(".slider").slider({
      animate: true,
      range: "min",
      value: 18,
      min: 18,
      max: 70,
      step: 1,
      slide: function(event, ui) {
        $("#slider-result").html(ui.value);
        document.getElementById(findElement('ageId')).value = ui.value;
      },
      //this updates the hidden form field so we can submit the data using a form
      change: function(event, ui) {
        $('#hidden').attr('value', ui.value);
      }
    });

    $(".PLUS").click(function() {
      var value = $("#slider-result").slider("value"),
        step = $("#slider-result").slider("option", "step");
      $("#slider-result").slider("value", value + step);
    });

  });
</script>

Any help is appreciated.

Answer

Mehmood picture Mehmood · May 20, 2016

If we check error in detail you will notice that it says you are trying to call the value method before the initialization of slider plugin.

Reason:

Actually JavaScript is an interpreted language, and it doesn't wait for first command to execute and finish. That's why your $(".slider").slider({ and $(".PLUS").click(function() { lines run at same time and the error occurs.

Solution:

You can put your code in setTimeout function here is an example given below.

<script>
  $(function() {
    $(".slider").slider({
      animate: true,
      range: "min",
      value: 18,
      min: 18,
      max: 70,
      step: 1,
      slide: function(event, ui) {
        $("#slider-result").html(ui.value);
        document.getElementById(findElement('ageId')).value = ui.value;
      },
      //this updates the hidden form field so we can submit the data using a form
      change: function(event, ui) {
        $('#hidden').attr('value', ui.value);
      }
    });

    setTimeout(function(){
      $(".PLUS").click(function() {
        var value = $("#slider-result").slider("value"),
          step = $("#slider-result").slider("option", "step");
        $("#slider-result").slider("value", value + step);
      });
    },200); // 200 = 0.2 seconds = 200 miliseconds

  });
</script>

I hope this will help you/someone.

Regards,