Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the field of vision?

Below is the code snippet:

$(document).ready(function(){
    $(window).bind("scroll", function() {
if ($(this).scrollTop() > 300) {
    $("#bluprintdesign").fadeIn();
} else {
    $("#bluprintdesign").stop().fadeOut();
}

Currently, the image fades in at 300px scrolled and fades out as you scroll back up. While this is effective, I would prefer it to be based on percentages for better responsiveness.

Appreciate any help or suggestions!

Answer №1

Presented here is a method titled showImages() which computes the scroll point of the bottom of the viewport by adding your $.scrollTop() to $(window).height(). This method adds a class to hidden images when half of the image has passed the bottom of the viewport. The function is triggered on both $(document).ready(); and $(window).on('scroll'); events to load images in the viewport during page load and while scrolling.

By utilizing opacity: 0 instead of display: none (used by $.fadeIn()/$.fadeOut()), you maintain the layout of the page as the image occupies space within the document. This approach allows for easy calculation of the image's height (critical for determining when half of it is in view) without any complex tricks, preventing page jumps that occur with toggling the display property.

There are various libraries available to automate this process. One popular option is jQuery waypoints.

function showImages() {
  var $window = $(window),
    thresh = $window.scrollTop() + $window.height();
  $('img:not(.show)').each(function() {
    if (thresh > $(this).offset().top + ($(this).outerHeight() / 2)) {
      $(this).addClass('show');
    }
  });
}
$(window).on('scroll', function() {
  showImages();
})
$(function() {
  showImages();
})
section {
  height: 200vh;
  border-top: 1px solid black;
}
img {
  opacity: 0;
  transition: opacity .25s;
}
.show {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <img src="http://kenwheeler.github.io/slick/img/fonz1.png">
</section>
<section>
  <img src="http://kenwheeler.github.io/slick/img/fonz1.png">
</section>
<section>
  <img src="http://kenwheeler.github.io/slick/img/fonz1.png">
</section>

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

Can a snapshot be taken of an auto-generated ID document in FireStore?

Currently, I am working on developing both a mobile app and web app for my Final Year Project. As someone relatively new to Firestore, I am using a single instance of it to store data. When a customer registers through the mobile app, their information ge ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

The window failed to redirect to the intended URL provided by the Json response

function GetOpenUrl(transactionId, legacyIndication) { var json = { id: transactionId, legacyIndication: legacyIndication }; $.ajax({ type: "POST", url: "<%= Url.Action("OpenSa ...

What is the best way to identify a specific AdWords account while utilizing campaignSelector within AdWords scripts?

I have been working on a script that aims to achieve the following tasks: Go through all the accounts in an MCC and pick out the ones with 'SEM' in their name. Go through the campaigns in a selected account and choose those that meet specific c ...

Can you explain how to create a function in Angular that accepts a number as an argument and then returns the square of that number?

I am working with an array of numbers and I want to show each number in the list along with its square value. To do this, I need to create a function that takes a number as input and returns its square as output. Here is what I have attempted so far: co ...

Could someone provide an explanation for this Jquery?

$(document).ready(function () { if ((screen.width >= 1024) && (screen.height >= 768)) { alert('Screen size: 1024x768 or larger'); $("link[rel=stylesheet]:not(:first)").attr({ href: "style2.css" ...

Verify whether a web application is equipped with React, Angular, or Vue

Is there an easy way to identify the client-side libraries used by an application if they are minified or compressed? While examining all the JavaScript sent from the server to the client, it can be challenging to determine if one of the top three popular ...

Issues arise when attempting to transmit JSON data from JavaScript to the server using the POST method

I'm having trouble viewing the JSON data I sent to the server using XMLHttpRequest. It seems like the server isn't receiving it because when I run the JavaScript, the alert window pops up but doesn't display anything. Does anyone have a solu ...

JavaScript is failing to update the table values as users interact with it

I've created an HTML table and used PHP to populate the values. The goal is to allow users to update order statuses with a status and message input. Initially it works fine, but after multiple uses, it either updates the wrong row or doesn't up ...

What steps can be taken to resolve the issue of the <td> element not being allowed as a child of an <a> tag?

https://i.stack.imgur.com/nsdA7.png How can I address these warnings? I utilized the material UI table component and suspect that the warnings are originating from component={Link} to={/patient/${patient.id}} <TableContainer className={styles.tableCo ...

Error: Angular encountered an unexpected token in the syntax

I am encountering an issue while trying to incorporate a user's profile updater on my website. Whenever I attempt to access a user's profile on the site, I run into this Angular error: main.ts:6 ERROR SyntaxError: Unexpected token 'e', ...

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

How to incorporate HTML 5 video into your Angular 2 project using Typescript

How can I programmatically start an HTML video in TypeScript when the user clicks on the video area itself? Below is my HTML code: <div class="video"> <video controls (click)="toggleVideo()" id="videoPlayer"> <source src="{{videoSource ...

express.js does not properly support the app.get functionality

app.get('/:id', function (req, res){ UserModel.find({ user: req.params.id}, function (err, user){ if (err) throw err; console.log(user + '\n\n'); res.render('profile.ejs', { ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

I'm new to Angular and I'm wondering how to close the panel by clicking on the 'x' button and also by clicking on the screen. Can anyone help me with this

Below is the HTML code I use for my button: <button class="btn btn-outlined " ng-click="vm.showCommentBox1()">Notify All</button> <div class="comment-box custom saveAll" ng-if=""><div class="panel panel-default"> ...

Are there any plugins available that can create a Ken Burns effect using JQuery?

All I need is a straightforward plugin, not one for creating slideshows. In this case, I only have 1 div and 1 image. The goal is to have the image animate within the div, shifting left/right or up/down without any white space visible. The size of the ima ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

What is the best way to integrate a Next.js Image component with a set width and an adaptable height in order to maintain the image's proportions?

This code snippet uses ChakraUI styling and retrieves images from SanityCMS: <Box w="500px" h="500px" bg="red"> <Image src={allArtPieces[0].imageUrl} alt={allArtPieces[0].title} width="500px" ...