DRB
DRB

Reputation: 653

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>

Upvotes: 7

Views: 4773

Answers (2)

adricadar
adricadar

Reputation: 10219

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>

Upvotes: 11

AmmarCSE
AmmarCSE

Reputation: 30587

First, replace

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

with

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

Instead of value use $(this).val()

See it working

Upvotes: 0

Related Questions