Prevent style attributes from changing back to default as others are change

Viewed 38

This snippet of code changes the brightness and contrast of an image. However, when setting the contrast to 150% for example and then attempting to change the brightness the contrast value defaults back to 100%. How can I prevent these style attributes from changing back to their default value after being changed?

<p>
   Contrast Bar
</p>
<input id='contrast_bar' type="range" min="50" max="150" value="100">
<p>
   Brightness Bar
</p>
<input id='brightness_bar' type="range" min="50" max="150" value="100">
<BR><BR>
<img id='img_selection' src="photo.jpg">
<script>
   let contrast_bar = document.querySelector('[id=contrast_bar]')
   let brightness_bar = document.querySelector('[id=brightness_bar]')
   let img = document.querySelector('#img_selection')

   contrast_bar.addEventListener('input', con_bar => {
     img.style.filter = 'contrast(' + con_bar.target.value + '%)'
   })

   brightness_bar.addEventListener('input', bright_bar => {
     img.style.filter = 'brightness(' + bright_bar.target.value + '%)'
   })
</script>
1 Answers

The problem is because you overwrite the previous setting of filter when you change each range slider, therefore only ever one filter type is updated.

To fix the problem create a function which reads the values from both range inputs and creates a single string with both brightness and contrast values, and call this function any time either range is changed.

let contrast_bar = document.querySelector('#contrast_bar');
let brightness_bar = document.querySelector('#brightness_bar');
let img = document.querySelector('#img_selection');
let updateFilter = () => img.style.filter = `contrast(${contrast_bar.value}%) brightness(${brightness_bar.value}%)`;

contrast_bar.addEventListener('input', updateFilter);
brightness_bar.addEventListener('input', updateFilter);
img { width: 300px; }
<p>Contrast Bar</p>
<input id="contrast_bar" type="range" min="50" max="150" value="100" />

<p>Brightness Bar</p>
<input id="brightness_bar" type="range" min="50" max="150" value="100" /><br /><br />

<img id="img_selection" src="https://i.imgur.com/WkomVeG.jpg" />

Related