Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a slider for opacity of a div

I'm having a bit of trouble having a slider change the opacity value of my div. Here is a fiddle of what I've been 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>
like image 832
DRB Avatar asked May 16 '15 04:05

DRB


1 Answers

You have to make use of change event. And to take the value of the slider like this ($(this).val(), not passing as parameter. This update the rectangle when you finished to choose 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>

For real time update you can use input event. This is updated when the value is changing.

// 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>
like image 183
adricadar Avatar answered Nov 15 '22 00:11

adricadar