Display Div when scrolling near the top, not the bottom

I found this code snippet on Stack Overflow that shows a div when the bottom scrolls into view. However, I need it to show the div when the top scrolls into view instead. How can I make this adjustment? Here's the JS Fiddle link

    $(document).ready(function() {
    $(window).scroll( function(){
        $('.hide').each( function(i){
            var top_of_object = $(this).position().top;
            var top_of_window = $(window).scrollTop();
            if( top_of_window < top_of_object ){ 
                $(this).animate({'opacity':'1'},500);     
            }   
        }); 

    });

});

Answer №1

Here's a simple solution. To make the animation trigger when reaching the top, use .animate(). Currently, you are calculating the bottom of the object with:

var bottom_of_object = $(this).position().top + $(this).outerHeight()

You can omit $(this).outerHeight() because it unnecessarily adds the height of the div to the y position for scrolling. Simply update it to:

var top_of_object = $(this).position().top

$(document).ready(function() {
  $(window).scroll(function() {
    $('.hide').each(function(i) {
      var bottom_of_object = $(this).position().top
      var bottom_of_window = $(window).scrollTop() + $(window).height()
      
      if (bottom_of_window > bottom_of_object)
        $(this).animate({ opacity: '1' }, 500)
    })
  })
})
#container { height: 2000px }
#container div { background-color: gray; margin: 20px; padding: 80px }
.hide { opacity: 0 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div>shown</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
  <div class="hide">Fade In</div>
</div>

Check out the fiddle here for future reference.

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

Changing the model does not automatically update the visibility of ng-show

I have a fragment of my view that simply displays a loading indicator. Html: <span class="app-loading-container"> <span class="app-loading-animation" ng-show="loading"></span> </span> When I initially load the page, the span ...

Mastering the art of smooth transitions between three animation sequence states using three.js in the animate loop

I want to achieve smooth transitions for the three different wing flapping sequences within a short period of time. Currently, the transitions appear abrupt as they jump from one state to another. The wings have 3 distinct states: 1) On the ground, 2) Flyi ...

Ways to adjust .keyup based on the presence of a variable

I am currently in the process of constructing a search form that utilizes an ajax function within .keyup, which may have various arguments. I aim to determine if a specific argument should be included based on the presence of another value. Here is my curr ...

Jquery Ajax Issue: The Page_Load method is running instead of the intended code

I have a method in my code that is supposed to return a csv file when called from the client side, but it currently just returns a simple string. public partial class ResourceEdit_PriceSheet : xCI.Site.Web.BasePage { protected void Page_Load( object s ...

Can someone please tell me how to convert this JavaScript regular expression into PHP code?

I created a JavaScript regular expression (regexp) and now I need it converted to PHP code: var alphaExp = /^[a-zA-ZåäöÅÄÖ\s\-]+$/; if (!fld.value.match(alphaExp)) { //ERROR OUTPUT HERE } Can someone provide me with the equivalent PHP c ...

Issues with PHP jQuery datatables ajax refresh functionality not working

After searching through numerous Stack Overflow posts regarding this issue, I am still unable to find a solution. Therefore, I am reaching out to you for help. My problem involves making an AJAX call to an external PHP file in order to retrieve the necess ...

Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example: function keepFirst(str, substr) { ... } keepFirst("This $ is some text $.", "$"); The expected result should be: This $ is some tex ...

When it comes to Redux, is it considered an anti-pattern to pass an event from a presentational component to a container component

As a newcomer to Redux, I am challenging myself to rebuild an old React app using this technology in order to gain proficiency. However, I am facing a significant challenge regarding where to place the logic within the application. My understanding is tha ...

How can JSON be formatted nicely on a webpage using JavaScript?

It appears to be a straightforward task for JavaScript to handle the pretty-printing of JSON. Has anyone come across or created a JavaScript function that can achieve this? ...

Is there an issue with the 'shardCount' parameter in this basic Webhook code?

I am attempting to dive into coding and learn more about API integration, but I keep encountering a frustrating error in my code: const Discord = require('discord.js') const webhookID = '888151030620106792'; const webhookTo ...

Guide to placing an image below a <div> using HTML?

Before diving into the creation of my website, I took the time to draft a wireframe using Balasmiq. You can take a look at the wireframe here. Upon reviewing the wireframe, you'll notice that the first section bears a semblance to this layout: https:/ ...

Customize border color for a single cell in a table using Bootstrap 4

I'm facing an issue where I'm trying to apply a red border color to a specific cell, but it's not appearing on the top and left sides of the cell. It seems like the border color of other cells is taking precedence over the one I'm tryin ...

The jQuery calls fail to execute in the update panel

My update panel is set to refresh every 1 minute. Within the panel, there are two input fields. When I click on each one, a datepicker function is triggered. Here are the scripts included for the datepicker: <link rel="stylesheet" href="http://code.jq ...

Step-by-step guide for setting up CodeMirror

I'm feeling a bit lost with what to do next: <link rel="stylesheet" href="lib/codemirror.css"> <script src="lib/codemirror.js"></script> <script> var editor = CodeMirror.fromTextArea(myTextarea, { mode: "text/html" }); ...

Only display the child component once the asynchronous function in the parent's mounted hook has finished executing

In my coding setup, there is a parent component that is responsible for rendering a child component. The challenge I am currently facing involves making an asynchronous call (specifically an axios 'get' request from Vuex actions) inside the mount ...

Adjust the Bootstrap date-time-picker to accommodate various languages, while ensuring that the selected date and time are displayed in English

As I work on my app, I've implemented localization support for multiple languages. When initializing the datetimepicker in the app, I provide the current language like this: datetimepicker({ locale: languageObj.language, format: 'DD MMM ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

What causes AngularJS to alter my GET parameters when using $http?

I am currently making a basic GET request to a REST service in order to obtain a list of users and sort them by their usernames. Using jQuery, the process runs smoothly: $.getJSON('/api/users', { sort: { username: 'asc' } }, funct ...

I encountered Hydration errors while attempting to use dangerouslySetInnerHTML to render a script on my webpage

My current solution involves utilizing dangerouslySetInnerHTML as a final attempt, as my script fails to execute properly. The specific format is necessary for the plugin to display on the frontend; otherwise, the console reports that ImageMapPro is undefi ...