Animation fails to initiate when the object enters the viewport

I attempted to inject some enchantment into my project by implementing code from a tutorial found on this CodePen. However, I encountered an issue where the code only functions properly within that specific CodePen environment. Even after copying the same code to another CodePen: here, it failed to work as expected. As I am not very familiar with jQuery, I would greatly appreciate any assistance.

Below is the JS file intended to detect if an element is in the viewport and then apply an animation to it:

//rewriting using prototype
//no jquery

$(function() {
  var $blocks = $('.animBlock.notViewed');
  var $window = $(window);

  $window.on('scroll', function(e){
    $blocks.each(function(i,elem){
      if($(this).hasClass('viewed')) 
        return;

      isScrolledIntoView($(this));
    });
  });
});

function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();
  var elemOffset = 0;

  if(elem.data('offset') != undefined) {
    elemOffset = elem.data('offset');
  }
  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  if(elemOffset != 0) { // custom offset is updated based on scrolling direction
    if(docViewTop - elemTop >= 0) {
      // scrolling up from bottom
      elemTop = $(elem).offset().top + elemOffset;
    } else {
      // scrolling down from top
      elemBottom = elemTop + $(elem).height() - elemOffset
    }
  }

  if((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
    // once an element is visible exchange the classes
    $(elem).removeClass('notViewed').addClass('viewed');

    var animElemsLeft = $('.animBlock.notViewed').length;
    if(animElemsLeft == 0){
      // with no animated elements left debind the scroll event
      $(window).off('scroll');
    }
  }
}

Answer №1

To make sure your code works properly on CodePen, don't forget to include jquery.min.js.

Here's how you can do it:

1. Go to your CodePen settings.
2. Navigate to the JavaScript section.
3. Add the following external scripts:
- https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js
- https://github.com/sstephenson/prototype/blob/master/src/prototype.js

After adding jQuery to my code on CodePen, everything is functioning as expected.

Check out the DEMO below:

// Rewrite the code using prototype instead of jQuery (no jQuery library needed)

// Function to check if element is in view
function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();
  var elemOffset = 0;
  
  if(elem.data('offset') != undefined) {
    elemOffset = elem.data('offset');
  }
  
  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();
  
  if(elemOffset != 0) {
    if(docViewTop - elemTop >= 0) {
      // Scrolling up from bottom
      elemTop = $(elem).offset().top + elemOffset;
    } else {
      // Scrolling down from top
      elemBottom = elemTop + $(elem).height() - elemOffset
    }
  }
  
  if((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
    // Swap classes when element is visible
    $(elem).removeClass('notViewed').addClass('viewed');
    
    var animElemsLeft = $('.animBlock.notViewed').length;
    
    if(animElemsLeft == 0){
      // Remove scroll event listener when no animated elements left
      $(window).off('scroll');
    }
  }
}
body{ height:1000px; width:auto;}

.block { 
  height:300px;
  width:300px;
  background-color:orange;
  margin-top:50px;
}

.animBlock {
  opacity: 0;
  filter: alpha(opacity=0);
  position: relative;
  -webkit-transition: all .55s ease-in;
  -moz-transition: all .55s ease-in;
  -ms-transition: all .55s ease-in;
  -o-transition: all .55s ease-in;
  transition: all .55s ease-in;
}
.animBlock[data-position="left"] { left: -20%; }
.animBlock[data-position="right"] { right: -20%; }
.animBlock[data-position="top"] { top: -20%;}
.animBlock[data-position="bottom"] { bottom: -20%;}

.animBlock[data-position="left"].viewed {
  left: 0%;
  opacity: 1;
  filter: alpha(opacity=100);
}
.animBlock[data-position="right"].viewed {
  right: 0%;
  opacity: 1;
  filter: alpha(opacity=100);
}
.animBlock[data-position="top"].viewed {
  top: 0%;
  opacity: 1;
  filter: alpha(opacity=100);
}
.animBlock[data-position="bottom"].viewed {
  bottom: 0%;
  opacity: 1;
  filter: alpha(opacity=100);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Author: Cory Harkins -->

<h1>This is a test of concept, scroll down...</h1>

<div data-position="left" data-offset="60" class="notViewed animBlock">
  <div class="block">in from left</div>
</div>


<div data-position="right" data-offset="60" class="notViewed animBlock">
  <div class="block">in from right</div>
</div>
<!-- decreased the offset here so square doesn't float in so quick-->
<div data-position="top" data-offset="0" class="notViewed animBlock">
  <div class="block">in from top</div>
</div>
<!-- increased the offset here so there isn't such a lag as it floats upwards-->
<div data-position="bottom" data-offset="300" class="notViewed animBlock">
  <div class="block">in from bottom</div>
</div>

<div data-position="left" data-offset="60" class="notViewed animBlock">
  <div class="block">
    <h1>Refresh to restart the animations</h3>
  </div>
</div>

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

Loading Kendo JS on the client side proves to be rather time-consuming

Working on my project, I have encountered a problem with the kendo ui scheduler where the downloading of the kendo js and css files on the client side is causing slowness on our website. To address this issue, we are attempting to download the kendo js and ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Controller action names combined with Web API route prefixes

My asp.net core 3.1 application has the following route in the startup file: app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id ...

Tips for attaching to a library function (such as Golden Layout) and invoking extra functionalities

I am currently utilizing a library named Golden Layout that includes a function called destroy, which closes all application windows on window close or refresh. My requirement is to enhance the functionality of the destroy function by also removing all lo ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

Tips for automatically closing a Bootstrap 3 modal when AJAX request succeeds?

I'm trying to close a modal upon ajax success, but I'm encountering an issue. Here is my code snippet: Javascript success: function() { console.log("delete success"); $('#deleteContactModal').modal('hide'); $( "# ...

Ajax: XML validation error is encountered

I have a task to use ajax call in order to read my xml file. However, when I attempt to do so, I encounter a parsererror. After validating my xml through a validator tool, it seems to be correct. Here is a snippet of my XML code: <?xml version="1.0" ...

Divide data into an HTML table and merge it with header information

My HTML form contains an interactive HTML table where users can add/delete rows. I am sending this data to a Google Sheet and need to store the row information with corresponding header details. Each time a user submits the form, a new row is added to the ...

How can you make an Angular directive activate only after the scope function in an ng-click handler has been executed?

Scenario I am relatively new to Angular and facing a specific challenge. The goal is to make a directive change the color and add an image to a button. However, I am struggling to get the first if condition to work in my Angular Directive. Issue The ob ...

Tips for determining the actions of a node prior to its inception

Is there a way to automatically run scripts on specific elements after their creation? For example, using a jQuery plugin like autoresize to expand the height of a textarea. If I use $('.textarea').autosize(), only the current textareas will be a ...

Create a fresh CSS class using the Chrome developer tool

Can a brand new CSS class be inserted in Chrome dev tools in this way? .myclass { background-color: yellow; } ...

The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event ...

How to modify ID data with AngularJS ng-repeat

I am currently searching for a solution to easily modify an ID within a repeated ng-structure. This scenario involves having a customer table with unique customer IDs, which are then utilized in another table related to orders. When I retrieve data from th ...

Guide on integrating next-images with rewrite in next.config.js

I'm currently facing a dilemma with my next.config.js file. I've successfully added a proxy to my requests using rewrite, but now I want to incorporate next-images to load svg files as well. However, I'm unsure of how to combine both functio ...

Manipulating and transforming data through Puppeteer's iterative process into an object structure

As a beginner with the puppetteer library, I'm trying to iterate through Amazon reviews and save each comment as an object. Although my code seems to be functioning, it only retrieves the first comment and then stops. async function scrapeProduct(ur ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

Using Angular to invoke the transclude directive function inside the transcluded component

I am looking to develop a component that includes a transcluded section, take a look at this example: http://jsfiddle.net/vp2dnj65/1/ Upon clicking the "do" button in the example, nothing seems to happen. Is there a way to execute the transcluded cont ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...