Html Range Element To Change Css Image Filter With Javascript
I am trying to use JavaScript to change an image's CSS filter when a user selects a new value on a range element. My HTML does not seem to work though. Here are my CSS image style
Solution 1:
Change onclick
event to onchange
in html and in javascript do this:
<script>var image = document.getElementById("Image");
var range = document.getElementById("Filter");
functionChangeFilter() {
image.style.WebkitFilter = "grayscale(" + range.value*10 + "%)");
image.style.filter = "grayscale(" + range.value*10 + "%)");
}
</script>
Solution 2:
You can find a working fiddle here.
There were a few problems in your code:
1) First of all, you should use the onchange
event instead of the onclick
event. Or you can use oninput
event as well.
2) The correct way of assigning new value of the filter to an Image object is Image.style.WebkitFilter="grayscale(10%)";
.
JavaScript:
functionChangeFilter() {
Image = document.getElementById("Image");
Filter = document.getElementById("Filter").value;
Image.style.WebkitFilter = "grayscale(" + Filter * 10 + "%)"
}
CSS
img {-webkit-filter: grayscale(100%); filter: grayscale(100%);}
HTML
<img src="https://upload.wikimedia.org/wikipedia/commons/f/fd/Pink_flower.jpg"id="Image" alt="Pineapple" width="300" height="300">
<form>
Photo Filter:
<input type="range"id="Filter" name="points" min="0" max="10" onchange="ChangeFilter()" />
</form>
Solution 3:
You need to wrap the grayscale value as a string.
I have simplified the code for you by using times, instead of ifs.
Also, you needed to set -webkit-filter
and if you are starting at 100%, set the value
to 10 to start with.
img {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
}
<imgsrc="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png"id="Image"alt="Pineapple"width="300"height="300"><form>
Photo Filter:
<inputtype="range"id="Filter"name="points"min="0"max="10"onchange="ChangeFilter()"value="10"></form><script>functionChangeFilter() {
var filter = document.getElementById("Filter").value;
var greyScale = 'grayscale(' + (filter * 10) + '%)';
document.getElementById("Image").style['-webkit-filter'] = greyScale;
document.getElementById("Image").style.filter = greyScale;
}
</script>
Post a Comment for "Html Range Element To Change Css Image Filter With Javascript"