jqueryfunctionif-statementinputplyr.js

How to add a class using less than from a range in input?


I'm having problems with my code. It's supposed to add a class called test to .js-volume when a range in an input is less than 30. It can work if the value in the input is exactly at 30 this.value == 30 but using less than or greater than doesn't work.

JS Code:

$(function() {
  $('.plyr-volume input').on('input',function(){
    if(parseInt(this.value > 30)) {
      $('.js-volume').addClass('test');
    } else {
      $('.js-volume').removeClass('test');
    }
  });
  $('.plyr__volume input').trigger('input');
})();

Demo - https://codepen.io/openbayou/pen/JQeEry


Solution

  • The this.value is actually returning decimals, so really the input is never going above 30 in your example, and wrapping it in a parseInt is making it return 0 no matter what.

    So you could do some conversions to return whole numbers, or you can just grab one of the attributes in the input, that has the "value".

    $(function() {
      $('.plyr-volume input').on('input',function(){
        // find the 'aria-valuenow' attribute, returns whole numbers
        var val = $(this).attr('aria-valuenow');   
        if(val > 30) {
          $('.js-volume').addClass('test');
        } else {
          $('.js-volume').removeClass('test');
        }
      });
      $('.plyr__volume input').trigger('input');
    });