Is there a way to modify a jQuery animation to be positioned in the center of an element?

I have implemented a fade animation on my web page using code from JS Fiddle. Currently, the element fades in when it is fully visible in the window. Is there a way to modify this code so that the fade animation starts when only half of the element is visible?

Below is the JavaScript responsible for triggering the animation:

/* This function runs every time the user scrolls */
 $(window).scroll( function(){
    /* Check the position of each element with the 'fade-in' class */
    $('.fade-in').each( function(i){
        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        /* If at least half of the object is visible, fade it in */
        if( bottom_of_window > bottom_of_object ){
            $(this).animate({'opacity':'1'},600);
        }
    });
});

Answer №1

Adjust the bottom_of_object value to be smaller than its initial height

var bottom_of_object = $(this).offset().top + $(this).outerHeight() / 4; //we divided by 4 at the end.

Answer №2

Make sure to adjust the bottom_of_object by half either in the if statement or during the calculation

 /* Whenever the page is scrolled ... */
     $(window).scroll( function(){
        /* Determine location of each specified element */
        $('.fade-in').each( function(i){
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            
            /* Fade in the object if it's completely visible in the window */
            if( bottom_of_window > (bottom_of_object / 2) ){
                $(this).animate({'opacity':'1'},600);
            }
        });
    });
    });

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

Activate a timer as soon as the page is first loaded. The timer must continue running from the initial load even if the user leaves

Looking to implement a time-limited offer on the first stage of our checkout process. The timer should start at 5 minutes when the page loads and continue counting down even if the user leaves the page and returns. Has anyone come across a script that can ...

What is the best way to read a .dat file in node.js and convert it into easily readable text or JSON format

I am facing an issue with a .dat file that contains information which is difficult to read. Therefore, my attempt was to open and convert this file into human-readable text or JSON format. Despite writing the code to read the file, I'm uncertain abo ...

The items in my array have been replaced with new objects

I am facing an issue with storing objects in an array within a function. Every time the function is called, a new object is received and I want to add it to the existing array without overwriting the previous objects. This way, all the objects can be acc ...

Is there a quicker method to update a div?

I'm looking for a more efficient way to refresh the contents of elements on my page every 5 seconds. The current code I have is functional but feels redundant and lengthy. Using just the setInterval function causes the page to not load consistently be ...

Having trouble with React list.map not functioning properly while deleting items from local storage?

I'm currently developing a budget tracking application that allows users to input various incomes and expenses. To manage the state of this app, I am utilizing useReducer. Each income and expense is represented as an object, and upon submission by the ...

Ways to send a variable to a component through history.replace

Is there a way to retrieve the match.chatroomId in a functional component? I am currently using history.replace to navigate to this component. Here is the code snippet: onClick = {() => history.replace(`/chat/${match.chatroomId}`)} ...

Creating a sleek CSS drop-down navigation menu

I seem to be facing an issue with the side navigation drop down menu. Below are the link and CSS code: <nav id="nav"> <div class="menu-main_nav-container"><ul id="menu-main_nav" class="menu"><li id="menu-item-270" class="menu-it ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

Show submenu in Bootstrap 4 dropdown on the right-hand side

I am working with a Bootstrap 4 multilevel dropdown menu and I am trying to figure out how to display the submenu on the right side of the parent dropdown, rather than just aligning it to the right. Any suggestions on how to achieve this? <script src ...

Techniques for altering history like the photo viewer on Facebook

On my website, I have a popup modal that functions similar to facebook's photo viewer. The issue is that when the modal is open, it displays content from another page, and I want to update the address bar value and history to reflect this change. Ins ...

Having trouble with positioning divs on top of each other? Struggling to get position absolute to work correctly?

Currently, I am utilizing flexbox to construct a grid layout. However, I have hit a roadblock when attempting to make the divs stack on top of each other. The overflow:auto is hidden and position relative has been added to the carddiv. While the divs are s ...

Ensure that PHP form validations are checked when submitting the form using jQuery

I have created a form in HTML with basic verification. Here is the code: <form class="" action="submit/save" method="POST" enctype="multipart/form-data" id="submit_form"> <input class="form- ...

Emitting events from a parent component to a child component

In the scenario mentioned above, using (click)="toggleSideBar()" in side-bar.component.ts does not close the sidebar. Is there a solution to this issue? ...

Choose an item from a list that does not have a particular class

Here is a list of items: <ul id='myList'> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li class='item-selected'>Item 4</li> <li>Item 5</li> & ...

When you import a mongoose schema into another schema file, the imported schema is not recognized and returns

Directory structure: │ resolvers.js │ schema.js │ └───schemas matchesSchema.js playersSchema.js teamsSchema.js tournamentsSchema.js I have 4 different schemas, and I want to utilize some of them in others ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

Focus on a specific data set within a JSON file when working with Backbone.js

Hello! I am new to learning Backbone.js and would love some suggestions from the experts out there. Here is a snippet of my code: app.Collections.UserCollection = Backbone.Collection.extend({ model: app.Models.IdModel, url: "/test/test_data.json" ...

What might be causing my checkboxes to become misaligned when viewed on mobile devices?

I am facing an issue with the layout of my checkboxes. They are coded as follows: <form> <div class="form-group"> <div class="row"> <div class="form-check"> <input type="checkbox" class="f ...

"Oops, it looks like there is a TypeError with this.props.tracks.map not being a function. Any ideas on why this might be

When passing information as props from one component to another, I encountered an error message in the TrackList component saying "TypeError: this.props.tracks.map is not a function". Can someone please assist me with this issue? This code snippet is from ...

Permuting sentences to create intricate anagrams

I am faced with a task of creating the correct phrase for a sentence anagram using an array of nearly 2700 strings. The list consists of almost 100k words that could potentially fit. My goal is to combine these words in groups of 1, 2, and 3 words togethe ...