jqueryrangesliderhideshow

Show and Hide Div based on range slider value using jQuery


I am trying to show a div when the input value reaches 2019 using a range slider. What am I doing wrong? is it something simple. Here is my JSfiddle

$(function() {
  $( "#slider" ).slider({
    value:2015,
    min: 2014,
    max: 2022,
    step: 1,
    slide: function( _event, ui ) {
      $( "#amount" ).val( ui.value );
    }
  });
  $( "#amount" ).val( $( "#slider" ).slider( "value" ) );
} );


$(document).ready(function() {
  
  $("#amount").on('change',function(){
    
    if (this.value == "2019") {
      $("#Red").show();
    }
    else {
      $("#Red").hide();
    }
  });         
  
}); 

and the DOM

<p>
  <label for="amount">Donation amount ($50 increments):</label>
  <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p> 

<div id="slider"></div>

<div id="Red" class="Box" style="background-color:red; height:100px; width:100px; display: none;">blach</div>

I was trying to figure out the code but I failed.


Solution

  • The change event isn't being fired when the value of the #amount input changes. To make sure it's triggered, you can programmatically force a change event on the #amount input in the function assigned to the slide property of your jQuery slider, like so:

    slide: function(event, ui) {
       $("#amount").val(ui.value);
       $("#amount").trigger("change");
    }