jQuery override opacity on an image with opacity set

I have an image with an inline opacity set like so...

<img id="theImage" style="opacity: 0.54;" src="...source..." class="gray-scale-img profileImage img-responsive"/>

I'm using IonRangeSlider to set a new value of the opacity but the issue is that if I go above 0.54 on my range slider the opacity does nothing. It will adjust fine from 0.00 to 0.54, but if I go above this, it just remains at 0.54 and will not get any brighter.

$("#theImage").css({ opacity: opacity });

IonRangeSlider

$("#formElement").ionRangeSlider({
  min: 0,
  max: 100,
  onChange: function(data) {
    var val = data.from;
    if (val < 100) {
      if (val < 10) {
        var opacity = "0.0" + val;
      } else {
        var opacity = "0." + val;
      }
    } else {
      var opacity = "1.0"
    }
    $("#theImage").css({
      opacity: opacity
    });
  },
  onFinish: function() {
    ...
  }
});

Thanks.

Answers 1

  • You are doing too many unnecessary calculations and branches with the opacity variable. It looks like you are trying to turn a percent into a decimal. Simply use data.from / 100 as your opacity value.

    $("#formElement").ionRangeSlider({
      min: 0,
      from: 54,
      max: 100,
      onChange: function (data) {
        $("#theImage").css('opacity', data.from / 100);
      },
      onFinish: function() {
        // stuff
      }
    });
    <input id="formElement" type="text" >
    <img id="theImage" src="//stackoverflow.com/favicon.ico">
    
    <!-- Resources necessary for the demo to work -->
    <link href="http://ionden.com/a/plugins/ion.rangeSlider/static/css/ion.rangeSlider.skinFlat.css" rel="stylesheet"/>
    <link href="http://ionden.com/a/plugins/ion.rangeSlider/static/css/ion.rangeSlider.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://rawgit.com/IonDen/ion.rangeSlider/master/js/ion.rangeSlider.min.js"></script>


    Edit: According to the documentation, you can configure your slider with the from property to set a default position. Credit to zer00ne for using this concept in his answer first.


Related Articles