Reputation: 202
I would like to adjust the css attribute of opacity
with a range input slider. If I have:
<div id="contrastFilter"> </div>
<div id="contrastSlider">
<input id="contrast" type="range" value="contrast" max="0.5" min="0" step="0.01"></input>
</div>
and I would like to change the opacity of this:
#contrastFilter{
background-color:black;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 2;
opacity: 0.2;
}
What javascript would I have to add to make this work? I would like the slider to affect the square's opacity.
Upvotes: 1
Views: 5597
Reputation: 8572
You could simply use input event:
$('#contrast').on('input', function() {
$('#contrastFilter').css('opacity', $(this).val());
});
#contrastFilter {
background-color: black;
width: 200px;
height: 200px;
position: absolute;
top: 20%;
float: right;
left: 20%;
z-index: 2;
opacity: 0.2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="contrastFilter"></div>
<div id="contrastSlider">
<input id="contrast" type="range" value="contrast" max="0.5" min="0" step="0.01"/>
</div>
Upvotes: 3
Reputation: 1804
First, you're going to need to revise your CSS. That z-index
on #contrastFilter
is going to render it above your input, making it unclickable.
Second, you'll need to add a listener to the input's change event, get the value, and update the opacity CSS of #contrastFilter
. I recommend using jQuery to facilitate cross-browser compliance.
CSS:
#contrastFilter{
background-color:black;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
opacity: 0.2;
}
#contrastSlider {
position: absolute;
}
JavaScript (using jQuery):
$(document).ready(function() {
$('#contrastSlider').change(function(e) {
var value = $(e.target).val();
$('#contrastFilter').css('opacity', value);
});
});
Forked fiddle: http://jsfiddle.net/Lmyoz94j/
Upvotes: 0