Reputation: 27
I am learning to make websites, and I have been struggling with this problem the entire day. I'd like to gradually blur an image when scrolling, then make it go back to the state from before when going back up
Here's a snippet from my css and html for the part that I want to blur:
.home-header {
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(write.jpg);
background-size: cover;
margin: auto;
}
.blur {
opacity: 0;
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
}
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<div class="home-header blur">
<div class="banner-text">
<p>Banner text</p>
<a href="#" class="btn btn-primary">Button</a>
</div>
</div>
<script>
$(document).ready(function() {
$(window).scroll(function(e) {
var s = $(window).scrollTop(),
opacityVal = (s / 200);
$('.blur').css('opacity', opacityVal);
});
});
</script>
Thank you!
Upvotes: 1
Views: 1704
Reputation: 10765
Your issue comes from the fact that you have opacity
set to zero on className
blur
, so nothing shows in the view. Since you clarified that you want to update the CSS
filter blur
as you scroll down, I have set opacity
to remain at 1.0 and modify the filter as you scroll. Please see the following snippet, I changed from division by 200 as that seemed like a lot to just division by 20 to demonstrate the affect you want. You can change this to whatever you deem necessary.
.home-header {
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(write.jpg);
background-size: cover;
margin: auto;
}
.blur {
opacity: 1.0;
-webkit-filter: blur(0px);
-moz-filter: blur(0px);
-o-filter: blur(0px);
-ms-filter: blur(0px);
filter: blur(0px);
}
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<div class="home-header blur">
<div class="banner-text">
<p>Banner text</p>
<a href="#" class="btn btn-primary">Button</a>
</div>
</div>
<div>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
L
<br/>
</div>
<script>
$(document).ready(function() {
$(window).scroll(function(e) {
let s = $(window).scrollTop(),
filterVal = s === 0 ? 0 : Math.ceil((s / 20));
$('.blur').css({
'filter' : 'blur(' + filterVal + 'px)',
'-webkit-filter' : 'blur(' + filterVal + 'px)',
'-moz-filter' : 'blur(' + filterVal + 'px)',
'-o-filter' : 'blur(' + filterVal + 'px)',
'-ms-filter' : 'blur(' + filterVal + 'px)'
});
});
});
</script>
Upvotes: 2