Zeli Zeli - 4 years ago 218
Javascript Question

Input range with contrast filter

I tried to create

input ranger
for apply contrast filter in div:

https://jsfiddle.net/ckekj8dn/

But it not working

Thanks for any help



$('#contrast').on('input', function() {
$('#mydiv').css('contrast', $(this).val() + "%");
});

#mydiv {
width: 400px;
height: 400px;
background-image: url("http://www.lorempixel.com/200/200/");
background-size: 100%;
border: solid 1px black;
background-repeat: no-repeat;
}

<div id="mydiv"></div>

Contrast
<input id="contrast" type="range" value="opacity_fundo" max="1" min="0" step="0.01" />
<br>




Answer Source

There is no contrast property in CSS. You're probably looking for the CSS3 filter property.

Since this property isn't supported in all browsers, you will need to add some prefixed properties for additional browser support. I added the -webkit prefix so that it works in Chrome/Safari. See this chart for browser support.

According to MDN documentation for the filter property, you can pass a percentage or a decimal. The input element returns a decimal, which means that you could simply use a decimal, or you could multiply the decimal by 100 and round it (i.e., Math.round(this.value * 100)).

Except where noted, the functions that take a value expressed with a percent sign (as in 34%) also accept the value expressed as decimal (as in 0.34).

As a side note, I also set the value of the range input element to 1 by default (since the contrast of the image is 1).

Updated Example

$('#contrast').on('input', function() {
  $('#mydiv').css({
    '-webkit-filter': 'contrast(' + this.value + ')',
    'filter': 'contrast(' + this.value + ')'
  });
});

It's also pretty simple to do this without jQuery:

Example Here

document.getElementById('contrast').addEventListener('input', function (e) {
  var element = document.getElementById('mydiv');

  element.style.webkitFilter = 'contrast(' + this.value + ')';
  element.style.filter = 'contrast(' + this.value + ')';
});

document.getElementById('contrast').addEventListener('input', function (e) {
  var element = document.getElementById('mydiv');
      
  element.style.webkitFilter = 'contrast(' + this.value + ')';
  element.style.filter = 'contrast(' + this.value + ')';
});
#mydiv {
  width: 200px;
  height: 200px;
  background-image: url("http://www.lorempixel.com/200/200/");
  background-size: 100%;
  border: solid 1px black;
  background-repeat: no-repeat;
}
<div id="mydiv"></div>

<label>Contrast:
  <input id="contrast" type="range" value="1" max="1" min="0" step="0.01" />
</label>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download