I’m working on a Blazor web app, and I would like to blur a specific element (background) when the user scrolls.
To achieve this, I called a JS function:
function backgroundBlurry() {
var distanceScrolled = document.scrollingElement.scrollTop;
$('.pageBackground').css({
filter: "blur(" + (distanceScrolled/10) + "px)"
})
}
My Razor page:
<body class="windowStyle" @onscroll="@Background">
<div class="pageBackground"/>
</body>
@code{
private async Task Background()
{
await _jsRuntime.InvokeVoidAsync("backgroundBlurry");
}
}
And here the classes of my css:
.windowStyle {
margin: 0;
user-select: none;
overflow: overlay;
width: 100%;
height: 100vh;
background-color: #1c2941;
display: grid;
align-items: center;
justify-items: center;
}
.pageBackground {
z-index: 0;
width: 100%;
height: 100%;
background-image: url(../res/image/web_background.webp);
display: grid;
justify-items: center;
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
position: fixed;
filter: blur(0px);
transform: scale(1.2);
}
My issue here, is the value for document.scrollingElement.scrollTop
returns 0 on Chrome, Edge and Firefox.
I tried with $(window).scrollTop()
, document.body.scrollTop
, document.documentElement.scrollTop
, and none of them worked.
Did I missed something?
Thank you.
Regards, Samih.
2
Answers
I came up with a solution, based on @clamchoda answer.
in the js script:
And in the css file, I removed
height:100vh;
.Before that, window.scroll was not working. After removing the height value, window.scroll worked, and scrollTop returns a correct value.
This solution worked for Chrome, Edge and Firefox.
Thanks to Clamchoda, and everyone.
Regards, Samih.
I think this would be easier using the scroll event. When scrolling is started add
.blurred
css to the element, and remove it when scrolling is stopped. It could look something like this.Html
Css
Javascript
JSFiddle I would use CSS transitioning to smooth out the effect.