Tips for fading an image as you scroll using CSS and JavaScript?

I have been dedicating my day to mastering the art of website development. However, I am facing a challenge that is proving to be quite difficult. I am looking to create a smooth transition effect where an image gradually blurs while scrolling down, and returns to its original state when scrolling back up.

Below is a snippet from my HTML and CSS related to the section I am working on:

.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>

Any help would be greatly appreciated!

Answer №1

Your current issue stems from setting the opacity to zero on the blur class, resulting in nothing being displayed. To address this and achieve the desired effect of updating the CSS filter blur as you scroll down, I have adjusted the code to maintain an opacity value of 1.0 and modify the filter dynamically based on scrolling. Below is the updated snippet with a change in the division value for demonstration purposes. Feel free to modify this as needed:

.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/>
   </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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning message in React about missing floating prop in components

application.js (Webpack Entry Point) import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render(<App /> ...

Issue with jQuery validate plugin (remote validation not working as expected)

Having trouble validating a user value with the jQuery Validation plugin. The validation appears to be working correctly and calling the web service function as intended. However, even when the server function returns a true/false result, the field is alwa ...

Angular Link function encounters scope undefined issue

I've been struggling with this issue for some time now. Imagine I have the directive and controller setup as shown below: angular.module('LiveAPP.artist',[]) .controller('artistCtrl', ['$scope', '$http', ' ...

Weird Chrome behaviors with CSS3 animations

I have been working on a CSS3 animation that involves rotating a div with an image in the background. My goal is to have the same animation play at a different speed when the user hovers over the element. Here is the code snippet I have been using: .roc ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...

Utilizing Redux dispatch to uncheck checkboxes within renderOption with Material UI Autocomplete

In the Autocomplete component, I have a checkbox that is rendered in the renderOptions prop. By using the onChange function event: object, value: T | T[], reason: string), I can retrieve the list of selected options. The value parameter will provide me w ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...

Utilize AngularJS's OrderBy feature to iterate through the list for navigation in ascending order by Index

I am looking to customize the order of an Object-array using ng-repeat based on their index keys in ascending order. $scope.paneContainer = {books:[{}] } ; $scope.paneContainer.books[0].science = { title:"science", content:"web/app/views/partials/scienc ...

Query to retrieve the most recent message from all users and a specific user resulting in an empty array

My goal is to retrieve all messages exchanged between User A and any other user. This is my schema structure: const MostRecentMessageSchema = new Schema({ to: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, from: { type: mongoose ...

Mobile view div failing to fill remaining space

When viewing my website on a mobile device, the heading in the div tag is not occupying the remaining space like it does on desktop. The heading is an h4 tag inside a div tag for mobile view. If you want to check out my website in inspect mode, here is the ...

Unusual issue encountered in next.js production: ENOENT error - File or directory not found (image cache)

Encountering an issue with my AWS EC2 deployment of next.js. After running npm run build followed by npm run start, everything appears to be functioning correctly. Initially, there are no webp images in the cache as expected. However, I have noticed that t ...

Learn the process of obtaining a location and showcasing it on Google Maps

I am working on creating a program that utilizes modernizer to ask for the user's location and then displays it using Google Maps. So far, I have been able to use geolocation to determine the coordinates of the user's location and attempted to in ...

Hello, I'm looking for assistance with this ReactJS code. Is there anyone who can help me

I am not receiving any output and also not encountering any errors, how can I resolve this issue? import React from 'react' function Array() { function myConcat() { const Villain = ["Harley Quinn", "Brainiac", "Deathstroke"]; cons ...

Tips for setting variable values in Angular 7

I'm encountering an issue with assigning values to variables in my code. Can anyone provide assistance in finding a solution? Here is the snippet of my code: app.component.ts: public power:any; public ice:any; public cake:any; changeValue(prop, ...

Omitting a portion of the key in JSON request with jQuery

Currently, I am populating some elements using JSON data. However, when a new JSON is loaded, the structure of the JSON appears slightly different. How can I ignore the initial part of the key to make it work? I thought about using an asterisk but that res ...

What is the best way to integrate TimeOut feature into an existing slider code?

I'm currently working on a simple slider with buttons that is functioning well. However, I am looking to incorporate the TimeOut() function into the existing code to enable automatic slide transitions. My attempts to achieve this using jQuery have be ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

Display dynamic content on the current PHP page using Ajax

I am currently facing an issue with sending data to the same php page using Ajax. The problem arises when I submit a form through Ajax, from a jQueryUI tab, and try to send the data back to the initially loaded php page in the tab. Below is the code snipp ...