I want to create a gradient effect using pseudo-element :before on an image that user would change by moving a slider input. I tried to get to it by following code, but no luck so far
var sliderValue = $('#range');
sliderValue.oninput = function(){
var val1 = this.value;
var val2 = 100-val1;
$('<style> #filter:before{linear-gradient(to top, rgba(255,255,255,1) '+val1+'%,rgba(0,0,0,0) '+val2+'%);}</style>').appendTo("#filter");
};
.slider
{
-webkit-appearance:none;
appearance:none;
width: 100%;
height: 10px;
max-width: 400px;
background-color: #ccc;
margin: 0;
padding: 0;
outline: none;
border-radius: 10px;
cursor: pointer;
}
#filter {
position:relative;
float: left;
max-height: 480px;
}
#filter:before {
content: "";
position:absolute;
top:0;
left: 0;
right: 0;
bottom: 0;
width:320px;
height:100%;
background: linear-gradient(to top, rgba(255,255,255,1) 15%,rgba(0,0,0,0) 22%);
z-index: 1;
}
<div class="container">
<input type="range" min="0" max="100" value="0" class="slider" id="range">
<div id="filter">
<img id="previewImg" src="img/dummy_320x480_ffffff_d002e2.png" alt="Placeholder" style="height: 100%; width:320px;">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
3
Answers
There are a few fixes that need to be made to the code for the gradient to work properly:
With these fixes, the code would look like this:
HTML:
jQuery:
CSS:
Remember that the tag is used to declare CSS styles in the header of the HTML page, and should not be used to dynamically create styles in jQuery. In the code above, we used the appendTo method to add the dynamically created CSS style to the #filter element.
Some problems with your code:
rgba(0,0,0,0)
torgba(0,0,0,.1)
so you’ll be able to see itAs noted in other answers, there were a number of problems with your initial code, primarily that you were trying to add a
<style>
element to the document on each occurrence of aninput
event fired on yoursliderValue
element. Unfortunately thatsliderValue
Object was a jQuery Object which had nooninput
method.To bind an event-handler with a jQuery Object the
on()
method should be used:However, while other answers have shown improved jQuery approaches I thought I’d take the opportunity to show you how this might be managed via plain JavaScript and CSS custom-properties as follows (with explanatory comments in the code):
JS Fiddle demo.
References:
aspect-ratio
.calc()
.clamp()
.display
.gap
.linear-gradient()
.var()
.data-*
attributes.[...]
).Array.prototype.forEach()
.document
.Event
constructor.EventTarget.addEventListener()
.EventTarget.dispatchEvent()
.