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

What is the safest way to convert a local file path to a file:// URL in Node.js?

In my node.js application, I am faced with the task of converting local file paths into file:// urls. After some research, I came across the File URI scheme on Wikipedia and I believe that there must be a solution out there or perhaps even an npm module t ...

Wait for the page content to finish loading before loading the Facebook Like Box

I am currently working on a method to delay the loading of the Facebook Like Box until after the page content has been fully loaded. My approach involves using AJAX, but I have encountered mixed results thus far. Initially, I used the following code snippe ...

Utilizing a loop for setting variable values in JavaScript

Using both JavaScript and JQuery. Let's imagine there is an array called ListArray with various sentences inside. Sounds easy enough. Is there a way to achieve this? var List = for (var i = 0; i < 10; i++) { //iterate over an array here to c ...

Fixed width for the last column in DataTables

Here's the scenario: I have a jQuery script that loads DataTables, and I know how to set the "aoColumns" : "sWidth" parameter to fix the width of a specific column, which is working fine. However, my issue arises from having multiple tables with var ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Error: Unable to retrieve the "error" property as the data is not defined

Encountered a title error and struggling to fix it :(. Attempting to retrieve data from a signup page, here is the snippet of my JavaScript code: const SignupComponent = () => { const [values, setValues] = useState({ name: 'ryan', emai ...

Moving pictures using css3 transitions

Trying to create a straightforward image slider. Below is the provided JavaScript code: $(document).ready(function() { $('#slide1_images').on('click', 'img', function(){ $("#slide1_images").css("transform","translateX ...

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

Adjust the size of multiple elements upon hovering over one of them

I encountered a puzzling issue, and here is a demonstration of my problem: https://jsfiddle.net/k1y8afst/ <div class="Sample"> <div class="Dummy"> <div class="Books"> <a st ...

Issue with JQuery executing PHP in Chrome extension

I have been attempting to retrieve the PHP result after using JQuery's post method within the context of a chrome extension. Unfortunately, all I am seeing is the unprocessed PHP code. Below is how I am calling the post method : $.post(chrome.extens ...

Not every child within a transition group in Vue.js is currently engaged in animation

This is the specific transition group that I have implemented <article class="hotel-row" v-for="hotel in paginatedHotels" :key="hotel.hotelid"> <search-hotel :hotel="hotel"></search-hotel> </article> If I do not assign unique ...

ReactJs allows for fluid scroll animations that persist as long as the mouse is clicked or a button

Just some background information: I'm aiming to replicate the scrolling effect seen in Etsy's product image thumbnails carousel. Essentially, when you hover over the top part of the div, it automatically scrolls down until the last image is reve ...

Resolved the z-index problem with the header and sidebar placement

Hello there! I have come across an issue that I need some help with. I have a fixed sidebar and header on my website, both of which have drop shadows applied to them. However, I don't want the header to cast a shadow on the sidebar as I want them to ...

Regular expression for precise numerical values of a specific magnitude (any programming language)

I have been searching for a solution to what I thought was a common problem but haven't found one yet. What I need is a regular expression that will fail on a specific number of significant figures (a Max), but pass for fewer than the Max. It should ...

Exploring a JSON file to generate a customized array for implementing autocomplete functionality in jQuery

I'm currently working on developing an autocomplete feature for a search bar that will display names of places in Norway. The data is being fetched from a REST API URL provided by a third party. As an example, when the input is "st" there are two res ...

Terminate a browser tab with the click of an HTML button

I'm facing an issue with my HTML button - I need it to close the tab upon clicking. Unfortunately, the common methods seem to no longer work on newer versions of Chrome and Firefox. I've tried using these two solutions but they did not work: & ...

Trouble with displaying the NVD3 sample chart

I seem to be missing something simple... I've copied the code for an nvd3 example exactly, but I'm getting a blank page without any error messages. Both the nvd3 and d3 libraries are showing up when I check in the console by typing "nv" or "d3", ...

The deep reactivity feature in Vue3 is functioning well, however, an error is being

I am currently using the composition API to fetch data from Firestore. While the render view is working fine, I am encountering some errors in the console and facing issues with Vue Router functionality. This might be due to deep reactivity in Vue. Here is ...

What is the process for incorporating an array of models?

let userData = await db.user.findOne({ attributes: attributes, include: ['charges', 'availability', 'practice',// 'services', 'education',// 'user_role', ...

The intricate dance between JAVA and HTML

Can Java be compatible with HTML and JS? Is it possible for them to cooperate without using JSP? In order to connect the WEKA function, we utilized Java code through a JAR file, but now we also require HTML and JS links for visualization. Is there an alte ...