Search code examples
jqueryrangeslider

Getting Range Slider value on Release (jQuery only, NO PLUGIN)


I have searched a few solutions but none of them solves the issue that I have.

I want to call another function only when the range slider is released. What I have so far is I have a simple range slider on which I put a check when it reaches certain value it should show alert, here's the code:

<input type="range" id="slider" value="0.5" min="0.0" max="1.0" step="0.01" />

$(document).on('input', '#slider', function() {
  $('#slider_value').html( $(this).val() );

  var ans = 0.50;

  if($(this).val() == 0.50){
  alert("ans");
  }


});

It shows alert as soon as it reaches 0.50, I want it like: User slides and releases and chooses a value and then alert should show, it some sort of a quiz.


Solution

  • Keep the input event for updating the value in the UI and add a new change event handler for the value check when the handle is released:

    $(document).on('change', '#slider', function() {
      if (parseFloat(this.value) == 0.5) {
        console.log("ans");
      }
    });
    
    $(document).on('input', '#slider', function() {
      $('#slider_value').html($(this).val());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="range" id="slider" value="0.5" min="0.0" max="1.0" step="0.01" />
    
    <div id="slider_value"></div>