Animate objects as they move along the page

Modern websites often incorporate animations into their designs. I had the idea to animate elements as we scroll down the page, using a combination of JQuery, HTML, and CSS.

<div class="noanimate imgleft">  
</div>
<div class="noanimate imgright">
</div>

The classes "imgleft" and "imgright" position elements to the left and right, respectively. The "noanimate" class initially hides elements with zero opacity and sets up transition properties for animation.

After creating the HTML structure, we apply the following CSS:

.noanimate{
    display:inline-block;
    opacity:0;
    transition:0.55s ease-in;
}
.imgleft.noanimate{
    left:-20%;
}
.imgright.noanimate{
    right:-20%;
}

This CSS code moves the elements 20% off-screen to create a floating effect. Now, let's look at the essential part - JQuery. We need to ensure that our animation is triggered only when the element is visible in the viewport.

A:- First, identify the elements and attach a window scrolling function.

var $section=$(".noanimate"),
$window=$(window);
$window.on('scroll',function(){
    $section.each(function(i,elem){
        if($(elem).hasClass('view')){
            return ;
        }
        else {
            checkView(elem);
        }
    }); 
});

B:- Check if the element is within the viewport by comparing its position relative to the window scroll.

function checkView(elem){
    var viewTop=$(window).scrollTop(),
    viewBottom=viewTop+$(window).height(),
    sectTop=$(elem).offset().top,
    sectBottom=sectTop+$(elem).height();

    if(sectTop>=viewTop && sectBottom<=viewBottom){
        switchClass(elem);
    }

    function switchClass(elem){
       $(elem).removeClass('.noanimate').addClass('view');
    }
}

If needed, you can also use JavaScript to handle older browser versions where CSS3 transitions may not work smoothly.

Check out this JsFiddle link for a demo.

Happy Coding :)

Answer №1

Hey everyone, I just made some adjustments to the code so that now it works for both scrolling up and down. Previously, it only loaded images when scrolling down.

Here is my updated version:

You can test it out here:

 $(function(){
     var $section=$(".noanimate");
     var $window=$(window);
     $window.on('scroll',function(){
       $section.each(function(i,elem){        
           checkView(elem);         
       });
     });

     function checkView(elem){
       var viewTop=$(window).scrollTop();
       var viewBottom=viewTop+$(window).height();
       var sectTop=$(elem).offset().top;
       var sectBottom=sectTop+$(elem).height();

       if(sectTop>=viewTop && sectBottom<=viewBottom){
        switchClass(elem);
       }else{
     switchClassBack(elem);
       }
       function switchClass(elem){
         $(elem).removeClass('.noanimate').addClass('view');
       }
       function switchClassBack(elem){
         $(elem).removeClass('view').addClass('.noanimate');
       }
     }
 });

You can view the demo on jsfiddle:

Check out the improved demo here

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 the value of each element in an array be modified if the items are not arranged in consecutive order (e.g. 0, 1, 2, etc.)?

I am facing a challenge with an array where items are stored using other elements' ID values instead of integers. I need to change the boolean values of each item in this array to 'false' when a button is clicked. Since my knowledge is limit ...

Impact of designs on the elements within components

Here's a CSS query I have: If I have the code below, does the styling apply to the contents of v-container but not v-container itself? <v-app id="inspire"> <v-container justify-center style="max-width: 1200px"> <v-layout row ...

Iterate over div elements using jQuery

I am experimenting with creating a jQuery slider using divs: <div id="block-1"> <div id="bannerleft"> <div class="wsite-header-1"></div> </div> <div id="bannerright"> < ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

How can we initiate the AJAX request right away while also making sure the page is fully loaded before adding

One trick I've discovered is that by submitting an AJAX request in the <head> section of my webpage, I can avoid a minor flicker on page load when loading content via AJAX. Of course, this method still needs some refining to handle longer AJAX r ...

What is the best way to dynamically implement text ellipsis using CSS in conjunction with Angular 7?

i need to display a list of cards in a component, each card has a description coming from the server. In my component.html, I am using a ngFor like this: <div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img- ...

Be patient for the execution of the addClass function

I'm currently facing an issue with jQuery. My goal is to make a single button perform two different actions based on the class. Despite its apparent simplicity, I've hit a roadblock in achieving this functionality. Here's what I have so far: ...

Retrieving JSONP using PHP does not yield results, only an object

Received JSONP response from an external domain: jQuery183012824459988766945_1354016515353([{"ID":"X1122","LName":"Smith","FName":"John"},{"ID":"X770","LName":"Johnson","FName":"Amy"}, {"ID":"X994", "LName": "Williams", "FName": "David"}, {"ID": "X580" , ...

Extract information from various webpages with identical URLs

I am struggling to extract data from a specific webpage (). Even though I can successfully gather information from the initial page, whenever I attempt to navigate to subsequent pages, it continues to display the same dataset. It seems to retrieve the iden ...

Cease the form submission process using Ajax when the input field is blank

I have implemented an ajax code that halts the form submission process if any input value is empty and displays a popup alert. However, I am facing an issue where the process continues even after closing the alert popup. How can I ensure that the process ...

What is the reason behind the inability to overflow the Safari viewport?

My website, , has a footer that is clickable in Chrome but not in Safari. When users scroll to the footer in Safari, the screen jumps back to the top, making it inaccessible. Can anyone help me identify the issue? Below is the CSS code for my React projec ...

Changing the visibility of a model in a method using the setVisible() method with Wicket Ajax

So in my code, I have: public class MyClass extends WebPage { static AjaxFallbackLink ddd = null; static AjaxFallbackLink dddd = null; (...) } Within the constructor, I have: ddd = new AjaxFallbackLink("previous") { @Override pub ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

Excessive text in HTML div element

Whenever I maximize the window in any browser, I type a long string in a div or span tag. It perfectly fits within the div tag. However, when I minimize or compress the browser width, the text spills out of the div area. I am looking for a solution to set ...

What causes the Object expected error in jQuery?

Looking for a way to demo horizontal collapse pane with a simple web page that includes html, css, and jquery. <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script> <title>Sa ...

Collaborating with Ladda button functionality

I have a button with ladda functionality, shown below. <button class="btn btn-primary btn-xs ladda-button" data-style="slide-left" data-size="xs" v-on:click="refreshPage()">Refresh</button> The onClick event is triggered by VueJs. When the b ...

Insufficient width of images in the bootstrap carousel

Is there a different solution to this problem that hasn't been mentioned in the other posts? I've tried all the top solutions from those posts, but my issue still remains. In particular, the "example" code and "Stock" bootstrap carousel appear t ...

Troubleshooting issue: jQuery not functioning as expected when used in

Currently, I have implemented a jQuery script that utilizes an ajax update method triggered by the focus event of a form element. The functionality is operational; however, I am encountering an issue when attempting to validate if the form element is empty ...

Received an undefined response from jQuery Ajax request to a webservice

I'm facing a small issue with my webservice call. I've thoroughly debugged it and confirmed that the webservice is being called with the correct value and returning the expected result. However, when I check the alert message in the completed fun ...