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

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

A step-by-step guide to incorporating VeeValidate with vue-i18n

When a click event is triggered, I am able to change the language in vue-i18n. However, I am facing an issue with changing the vee-validate dictionary to match the same language. Main.js import VeeValidate from 'vee-validate' import validations ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Error message encountered in Express.js when trying to apply the ejs function: "View is not a constructor"

I am attempting to execute certain tasks before the original app.get function is called. After referring to this page, I applied their method which worked for the most part, except when using a rendering engine. The code snippet below demonstrates what I ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Retrieving a list from an ASP.NET MVC controller using ajax

After searching for a solution to my problem on search engines and Stack Overflow, I came across various answers but none of them seemed to work for me. Here is the code snippet from my controller: [HttpGet] public JsonResult Get() { var c ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Converting HTML Form Data into CSV with Multiple Rows

I currently have a form that generates a CSV file with data from select elements in the HTML form. The columns in the CSV correspond to the selected options in the form, but I need to extend this functionality to populate multiple rows in the CSV. Expecte ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...

What are the steps to correctly implement async await in a standard sequence?

When I press the button onPress={() => Login()} First, I need to obtain a token by using the signInWithKakao function. Secondly, right after acquiring the token, if it is available, I want to dispatch the profile using the kakaoprofile function. However, ...

jQuery must provide the complete object rather than just the data within it

What is the best way to retrieve the entire <div class="loan_officer_apply_now_link"><a href="">APPLY NOW!</a></div> At present, only the "a" element content is being returned <a href="">APPLY NOW!</a> Test Code $( ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Sending files through ajax with php

Hey there! I've been working on uploading files using Ajax and PHP, following a tutorial. Here's the code I have so far: upload.js: var handleUpload = function (event){ event.preventDefault(); event.stopPropagation(); var fileInput= document.ge ...

Utilizing Selenium to automatically scroll through a Flickr page in order to capture and retrieve all the

Hey there! I'm currently working on a project to retrieve Flickr public images from a specific group. So far, I've been able to successfully parse the HTML and extract the image hrefs. However, I'm facing a challenge when it comes to retriev ...

What is the best way to reduce the size of an image using a URL?

As I work on creating a website in React for a company, my main focus is on developing a drive repository where users can upload files. One issue that has arisen is the performance of the "photos" folder, as it contains numerous high-resolution images th ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Designing Checkboxes and Radio Buttons

I am seeking a way to customize the appearance of checked and unchecked checkboxes using images without modifying the HTML structure. I would prefer not to add labels, classes, or IDs to the elements. The provided example only works in Webkit browsers, s ...