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

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

Once the promise program enters the if-condition, even though the condition itself is actually false

There seems to be an issue with retrieving the location code using the AccuWeather API before getting the weather data for a city. Despite the location array being empty, the program still proceeds to a branch that expects a non-empty array. router.get(& ...

What is the best way to generate a ul-li structure using JSON input and jQuery?

There is a JSON variable present: var links=[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home","children":[{"text":"home2","href":"home2.com","icon":"fas fa-chart-bar","target":"_self","title":"home2","category ...

Are Your Padding Styles Missing?

I've noticed that the text under the photos on this page in the main section (a.event) is not displaying the 5px padding top and bottom. Any suggestions for fixing this? Thank you! =) a.event { width:315px; height:auto; border:0; padding: 5px 0; } ...

Is there a way to arrange the components of my form so that the questions are positioned on the left side and the choices are displayed on the right

As I am creating a form, my goal is to align the information within it in a way that places the questions on the left side and the options on the right. I have experimented with utilizing IDs, centering them, and adjusting their positioning from left to r ...

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

The element is unclickable due to being obstructed by another element

https://i.sstatic.net/pomMS.png My task is to click on a button using this code: browser.find_element_by_id('btnSearch') However, the button is being blocked by a div tag with the following attributes: <div id="actionSearch" class="row pull- ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

Ways to resolve the error message "Uncaught TypeError: props.options.map is not a function occurring when using a dropdown select

While working on my project, I encountered a strange error with the react select dropdown. Despite following suggestions online to pass an array of objects as options, I'm still facing the same issue. Surprisingly, when I directly input the data fetch ...

How can I activate a radio button by its corresponding label using Selenium?

After diving into the world of automation with Selenium in C#, I find myself faced with a challenge. I need to automate clicking on a specific radio button on a website based on the text of the associated label. What makes it even more interesting is that ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

Encountering an error with ResizeObserver.observe when using Next.js and ag-grid to render client side

I designed a product page that includes a searchbar component and a grid component with the ag-grid import and setup. Here is a simplified version of the product page: // Code for dynamic client side rendering import const ProductGrid = dynamic(() => ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

"Troubleshoot: Why is the Position Absolute Not Functioning in

Trying to achieve a layout similar to the last element at the bottom of the footer] 1, but getting something like this instead: https://i.sstatic.net/lXazk.png <footer> <div class="container-fluid"> <div class="row"> ...

Activating Jquery toggle on several elements instead of just the specified element

Hey everyone, I have a question regarding jQuery. I have a toggle function that is supposed to activate when clicking on a specific element - in this case, my logo image with the id of #logobutton. The toggle works great, but there's a problem. The an ...

What is the method for applying a Redux statement?

Experience with Redux toolkits: I've encountered an issue while working with Redux toolkits where I'm unable to access certain statements. I attempted the following code snippet, but it resulted in an error. const orderDetails = useSelector(( ...

Internet Explorer 7 does not support the return link feature when using jQuery

My issue involves using jQuery and Ajax, where my Ajax.php file outputs a specific field into the main file. Everything works as expected when I click in Mozilla and Chrome, resulting in an alert pop-up. However, when attempting the same action in Internet ...

Mongoose consistently fails to properly save dates

I have created a Mongoose model and included a birthdate field in the following way: birthdate: { type: Date, required: [true, "Please enter a birthdate"], lowercase: true, validate: [isDate, "Please enter a valid birthdate&q ...

What are the security risks of evaluating user-supplied strings in web browser storage?

I'm in the final stages of developing a script that creates an API for performing storage operations across various web browser storage technologies. Currently, I am focusing on adding conditional retrieval and removal functionalities. These features ...