skip to Main Content

I am using jQuery to check the value of a range slider, and if that value is 1, add a class to an other element. The code below works well for this:

$(document).ready(function() {
  $("#range-slider").mousemove(function() {
    if (this.value == "1") {
      $('.other-element').addClass('is--active');
    } else {
      $('.other-element').removeClass('is--active');
    }
  });
});

However I’d like to do this for multiple values, but the below code does not work. So how can I achieve this?

$(document).ready(function() {
  $("#range-slider").mousemove(function() {
    if (this.value == "1", "2", "3", "4", "5") {
      $('.other-element').addClass('is--active');
    } else {
      $('.other-element').removeClass('is--active');
    }
  });
});

3

Answers


  1. You need to check if the list of values includes this.value :

    $(document).ready(function() {
      $("#range-slider").mousemove(function() {
        if (["1", "2", "3", "4", "5"].includes(this.value)) {
          $('.other-element').addClass('is--active');
        } else {
          $('.other-element').removeClass('is--active');
        }
      });
    });
    
    Login or Signup to reply.
  2. If you’re looking to add a class to an element depending on the range slider’s value, here’s the code:

    $(document).ready(function() {
      $("#range-slider").on('mousemove', function() {
        var value = parseInt($(this).val());
        if (value >= 1 && value <= 5) {
          $('.other-element').addClass('is-active').html(`Slider Active Value is: ${value}`);
        } else {
          $('.other-element').removeClass('is-active').html(`Slider Value is: ${value}`);
        }
      });
    });
    .other-element {
      margin-top: 20px;
      padding: 10px;
      background-color: #f1f1f1;
      transition: all 200ms ease;
    }
    
    .other-element.is-active {
      background-color: lightblue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <input type="range" id="range-slider" min="0" value="7" max="9">
    <div class="other-element">value</div>
    Login or Signup to reply.
  3. You can use the following if you want the action to happen for a certain range (10…20):

    $("#range-slider").on("input",function(){
      $(".other-element").toggleClass("active",this.value>9&&this.value<21)
    })
    .active {background-color:green}
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <input type="range" id="range-slider" min="0" max="50" value="5" step="1" />
    <span class="other-element">in range</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search