Nyx
Nyx

Reputation: 314

Input range - on value increase (value++) vs on value decrease (value--)

I am testing a script that includes a range slider and I ran into a problem while trying to return a different output depending on the range value, here is what I mean by this...

$('document').ready(function(){
$('#controller').on('input', function(){
    let value = $('#volume').val();
    if(value++){
        console.log('Value Increased');
    }
    else if(value--){
        console.log('Value Decreased');
    }
});
});

Now, what happens is that no matter if you increase or decrease the value of the slider it always returns "Value Increased" except in case when you put the slider on 0 in which case it returns "Value Decreased"...

This is my first time working with range sliders, any help is appreciated!

Upvotes: 1

Views: 360

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because value++ and value-- will always return an integer, not a boolean value. Using a non-zero integer in an if condition will always coerce to true, hence you always see 'Value increased' unless the value is 0.

To do what you require the correct logic would be to store the previous slider value and compare it to the latest one, like this:

let oldValue = $('#controller').val(); // set when the DOM loads

$('#controller').on('input', function() {
  let currentValue = $('#controller').val();
  if (currentValue > oldValue) {
    console.log('Value Increased');
  } else if (currentValue < oldValue) {
    console.log('Value Decreased');
  } else {
    console.log('No change');
  }
  oldValue = currentValue;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" id="controller" min="0" max="100" />

Upvotes: 1

Related Questions