Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event at end of onchange for input type range

How to trigger an event or detect the end of onchange event for input type range.

$('.slider').on('change',function(e){
      console.log(e.target.value);
});

Now this will return a number of console logs when I start dragging the range input. I wanted to get the value at the end of onchange event. How to achieve this ?

Thank you ;)

like image 636
Gururaj Bhandarkar Avatar asked May 19 '17 08:05

Gururaj Bhandarkar


2 Answers

Hey Gururaj you can try debounce function. It delays the firing of your event handler so you can get your input value at the end of onchange event as you want it. Lodash has a implementation of the debounce function you can use.

$range.on('change', _.debounce(function() {
  $display.text($(this).val());
}, 250));

Here's a little demo for you.

like image 63
dawchihliou Avatar answered Sep 30 '22 00:09

dawchihliou


you can use mousedown and mouseup something like this

var prevValue = 0;
$('.slider').on('change',function(e){
      
});
// mouse down to check for previous value
$('.slider').on('mousedown',function(e){
      prevValue = $(this).val();
});
// mouse up when the mouse up from the slider with end value
$('.slider').on('mouseup' , function(){
    var ThisValue = $(this).val();
    if(ThisValue !== prevValue){  // check new value with previous value
    	alert('Value Changed');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="slider" type="range" min="0" max="100"/>

For complete answer as an example above using mouseup and mousedown events this is if you need to compare a previous value with new value and like JYoThI said i think on change event is enough to get last values of range

Additional Information you can use input event if you need to update the div value on realtime

Working Demo

$('.slider').on('change',function(e){
      console.log($(this).val());
});

//update sliderCount div with real time value
$('.slider').on('input',function(e){
      $('.sliderCount').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="slider" type="range" value="50" min="0" max="100"/>
<div class="sliderCount">50</div>
like image 30
Mohamed-Yousef Avatar answered Sep 30 '22 00:09

Mohamed-Yousef