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

Connect ng-models with checkboxes in input field

I am facing an issue with binding ng-models using ng-repeat in an input checkbox tag. Let me share my code and elaborate further. app/main.html: <div ng-repeat="feature in features"> <input type="checkbox" ng-model="features[$index].name"> ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

"Patience is key as we wait for the successful completion of the ajax

My dilemma involves an ajax call that looks something like this: $.ajax({... Within the success callback, there is a line of code similar to: var editor = $find("<%= NewsDetail.ClientID%>"); I need to delay the execution of this $find() function ...

The div within the button is failing to properly adjust to height settings

Check out this Fiddle I'm currently working on a social thumbs up button and I've encountered some challenges. In my button design, I have included a second div to accommodate the right side of it. However, despite trying to adjust its height us ...

Disappearance of icon upon hovering in CSS

I am currently working with Angular JS (1.x) and I have a requirement to display tooltip text when hovering over an info icon. The tooltip text appears properly, but the issue is that the icon disappears when hovered over. It reappears once the hover is re ...

Issues within html language

The formatting of this table is causing issues with printing <tr height="95%"> <td width="100%"> <div id="placeSchedule"> <table bgcolor="red" width="100%" height="100%" border="1"> <tr> < ...

What is the best way to connect my data with my Backbone Views?

I have successfully set up my views to show test data, and now I want to implement asynchronous data loading to fetch real information. However, I'm a bit confused on the best method to achieve this. Should I manually create AJAX calls? Or maybe utili ...

Is the admin_init hook in Wordpress triggering multiple times?

Encountering an issue on my Wordpress website where admin_init is being called twice has been quite a headache. After deactivating all plugins, I managed to pinpoint the culprit plugin that was causing the problem. Now my dilemma is how to determine the ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

Alignment of a Definition List with Omissions of Definitions

Often, I come across applications with forms containing optional fields. In the Show view, these fields tend to "collapse" together and lose alignment with their corresponding labels. For instance, if I have 3 fields that should be displayed as: Phone: 3 ...

How to extract a div from its parent using jQuery

I need to stack two div boxes on top of each other, and my goal is to hide the upper one when it's being hovered over. HTML: <div id="left_middle"> <div id="rfinder_UP"></div> <div id="rfinder_DWN"></div> </div> C ...

Converting Markdown to HTML using AngularJS

I'm utilizing the Contentful API to retrieve content. It comes in the form of a JSON object to my Node server, which then forwards it to my Angular frontend. This JSON object contains raw markdown text that has not been processed yet. For instance, t ...

Add a captivating backdrop to a div element

So I have this unique HTML element that showcases a large headline with two decorative lines on either side, extending to the full width of the element. However, I now have a requirement to display some text as a background behind this element. The issue ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

What is the correct way to utilize "data:" in a jQuery AJAX call?

There seems to be an issue with my code within the deletePost function. The problem lies in the fact that $_GET['title'] is empty. Although I set the title value in the ajax using postTitle: $(this).siblings("h3.blog").text(), it doesn't see ...

What causes the variation in the appearance of the navigation bar across different pages?

I'm struggling to understand why the Navigation bar has extra padding or margin on top only on certain pages, while it looks fine on the Homepage. I've dedicated countless hours to this issue and I am feeling completely frustrated. If you' ...

Twofold Arrow Styling in CSS

Can someone help me achieve this design: https://i.stack.imgur.com/eBQ1a.png I am attempting to create a double arrow using just one class. I have tried various methods, but nothing seems to be working for me. If anyone has any suggestions or can point ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

How plupload can seamlessly transition to the next upload after completing one

Using plupload 1.5.7 and the jQuery Queue Widget, I've noticed that after completing an upload, the Add files and Start Upload buttons disappear, replaced by a label saying Upload 1/1 files. Unfortunately, this means I can't add more files witho ...

How to stop the overflow scrollbar in a grandchild element with CSS grid

Encountered an unusual issue while using a combination of CSS grid and overflow auto. In the scenario where there are 3 elements, the outermost element has display: grid, the middle element has height: 100%, and the innermost element has both height: 100% ...