I'm trying to unblur an image when scrolling. But when I add position: fixed; property to my CSS class the image is not getting displayed.Also the JS is giving an error saying 'scrollPercent not defined'. My inspiration to this code is :codepen
$(document).ready(function() {
$(window).scroll(function() {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
scrollPercent = (s / (d - c)).toFixed(2);
// opacity value 0% to 100%
$('.clear-img').css('opacity', scrollPercent);
});
});
.imgsrc {
position: fixed;
background-position: center;
webkit-background-size: cover;
width: 100%;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: -1;
}
.clear-img {
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blurred-image-container">
<div class="imgsrc">
<img src="https://cdn.glitch.global/ea44df9f-5322-47c9-83ba-4f453113a115/blur.png?v=1651333241542" />
</div>
<div class="imgsrc clear-img">
<img src="https://cdn.glitch.global/ea44df9f-5322-47c9-83ba-4f453113a115/unblur.png?v=1651333316753" />
</div>
</div>
Did you include jQuery correctly?
It looks ok to me (I added a height: 1200px to body to allow for scrolling inside the snippet):
$(document).ready(function() {
$(window).scroll(function() {
const s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
const scrollPercent = (s / (d - c)).toFixed(2);
// opacity value 0% to 100%
$('.clear-img').css('opacity', scrollPercent);
});
});
body {
height: 1200px;
width: auto;
}
.imgsrc {
position: fixed;
background-position: center;
webkit-background-size: cover;
width: 100%;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: -1;
}
.imgsrc img {
width: 100vw;
}
.clear-img {
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blurred-image-container">
<div class="imgsrc">
<img src="https://cdn.glitch.global/ea44df9f-5322-47c9-83ba-4f453113a115/blur.png?v=1651333241542" />
</div>
<div class="imgsrc clear-img">
<img src="https://cdn.glitch.global/ea44df9f-5322-47c9-83ba-4f453113a115/unblur.png?v=1651333316753" />
</div>
</div>