Using slider for opacity div

I had a little problem when the slider changed the opacity value of my div. Here is the scenario of what I was working with: https://jsfiddle.net/yfmLk1ad/1/

$('#bgopacity').on('slide', function(value) { $('.background-color').css({ opacity: value * '.01' }); }); 
 .background-color { width: 500px; height: 500px; background: red; opacity: .5; } 
 <div class="background-color"></div> <form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output> </form> 
+6
source share
2 answers

You need to use the change event. And take the value of the slider like this ($(this).val() , not passing as a parameter. This is an update to the rectangle when you are finished to select the value.

 // Opacity Slider $('#bgopacity').on('change', function (value) { $('.background-color').css({ opacity: $(this).val() * '.01' }); }); 
 .background-color { width: 500px; height: 500px; background: red; opacity: .5; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output> </form> <div class="background-color"></div> 

You can use the input event to update real-time . This is updated when the value changes.

 // Opacity Slider $('#bgopacity').on('input', function (value) { $('.background-color').css({ opacity: $(this).val() * '.01' }); }); 
 .background-color { width: 500px; height: 500px; background: red; opacity: .5; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label>Color Opacity</label> <input type="range" name="bgopacity" id="bgopacity" value="50" min="0" max="100" step="1" onchange="rangevalue.value=value"> <output id="rangevalue">50</output> </form> <div class="background-color"></div> 
+10
source

Replace first

 $('#bgopacity').on('slide', function (){...}); 

with

 $('#bgopacity').on('change', function (){..}); 

Use $(this).val() instead of value

See working

0
source

Source: https://habr.com/ru/post/987321/


All Articles