Add dynamic animation effects to a section as it comes into view with the power of JavaScript

As I continue to learn about web design, I am interested in creating an animation on a div element located in the middle of the page. Most resources I have come across suggest using jQuery for this task. However, I am wondering if it is possible to achieve this with just CSS and JavaScript.

<div>This div contains a lot of content that takes up the entire screen</div>
<div>The animation should occur when this div comes into view</div>

I would greatly appreciate any guidance on whether it can be accomplished solely with JavaScript, and if not, what the simplest approach would be.

Answer №1

I just conducted a search like yours and stumbled upon a purely js solution

CHECK THIS OUT

var elements;
var windowHeight;
document.getElementById('content').innerText = "A lot of content to fill up the page. ".repeat(500)

function init() {
  elements = document.querySelectorAll('.noanimfornow');
  windowHeight = window.innerHeight;
}

function checkPosition() {
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    var positionFromTop = elements[i].getBoundingClientRect().top;
//console.log(positionFromTop,windowHeight);
    if (positionFromTop - windowHeight <= 0) {
      element.classList.add('animateme');
      element.classList.remove('noanimfornow');
    }
        if (positionFromTop - windowHeight > 0) {/*newly added:Edit2*/
      element.classList.add('noanimfornow');
      element.classList.remove('animateme');
    }
  }
}

window.addEventListener('scroll', checkPosition);
window.addEventListener('resize', init);

init();
checkPosition();
@keyframes myanim {
  from {
    opacity: 0;
    transform: scale(.7, .7)
  }
  to {
    opacity: 1;
  }
}

.animateme {
  animation: myanim 5s;
}
.noanimfornow {
  opacity: 0;
}
<div id="content"></div>

<div class="noanimfornow">Section where animation has to happen when come into view</div>

  • To trigger animations only on scroll, use the class noanimfornow for the respective div,
  • In the JavaScript code, we monitor scroll positions and switch classes to animateme when in view,
  • We also handle resizing events by calling the init function as needed in JavaScript,
  • Lastly, add some CSS animations for visual effects

Answer №2

This response performs the same function as the previous one, but it utilizes IntersectionObserver

  • Hence, there is "No need to input JS on every scroll." - Comment by A. Haworth

This Code was sourced from this site

  • I have also incorporated Tschallacka's modification to eliminate copy-pasting (utilizing .repeat(500) in js)

var elements;
var windowHeight;
document.getElementById('content').innerText = "A lot of content to fill up the page. ".repeat(500)

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    const square = entry.target.querySelector('.noanimfornow');

    if (entry.isIntersecting) {
      square.classList.add('animateme');
      return; // if we added the class, exit the function
    }

    // We're not intersecting, so remove the class!
    square.classList.remove('animateme');
  });
});

observer.observe(document.querySelector('.animwrapper'));
@keyframes myanim {
  from {
    opacity: 0;
    transform: scale(.7, .7)
  }
  to {
    opacity: 1;
  }
}

.animateme {
  animation: myanim 5s;
}

.noanimfornow {
  opacity: 0;
}
<div id="content"></div>
<div class="animwrapper">
  <div class="noanimfornow">Section where animation has to happen when come into view</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

Prevent any delay between two video segments

Revised after being placed on hold My objective is to seamlessly play video files back-to-back without any transitions. Due to limitations on the Raspberry Pi, I am currently using omxplayer to achieve this. I have chosen to write my code in node.js as i ...

Guide for skipping the presentation of data in column1, when column2 contains multiple lines of content

How can I avoid showing redundant data for ItemA when ItemB has multiple lines to display: ItemA = [Color Fruit, Nuts] ItemB = [[green], [orange, apple, grapes], [cashew, almond]] if (this.point.customTT === 'Item') { ...

Multiple event listeners on a single button

I'm working on implementing GATracking for a group of pages. I want to track both pageloads and clicks on specific buttons. My goal is to create code that is easily adaptable without the need for extensive rework. Some functions already have bindings, ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

How to utilize jQuery to highlight active anchor tag in an ASP.NET environment

I am attempting to modify the color of a list item when an anchor tag is clicked using jQuery. When I call a C# function from the code-behind on clicking the anchor tag, if I include "return false" in the jQuery code as shown below, the color changes but t ...

What is the best way to create a clickable <li> element from AJAX search results that display dynamic HTML?

Utilizing AJAX technology, I have implemented a live search feature that populates results from a database as the user types in a text field. The results are presented in an unordered list format. My goal is to allow users to click on an item within the li ...

Is it possible to filter a single field for two different values in a relationMapping using Objection.js?

In an Objection.js model, I have a relation mapping where I need to set a filter on a field that can only have two possible values: null or 0. Here is an example of the relation I am using: static get relationMappings() { return { dipendenti: { ...

Tips for redirecting to the index page instead of the login form after pressing the back button on the navigation

Hey everyone! I've been struggling with a problem for the past 4 hours and could really use some help. After logging in, the page redirects to a certain page, but when I press the back button in my browser, I want it to redirect back to that specific ...

Transmit a combination of selection and text inputs through AJAX to PHP, and then save the data in a

Is it possible to send multiple inputs (one text and one select multiple) via AJAX to a PHP file? The data is successfully sent using form serialize, as evidenced by the complete array in prod_multi when logging with console.log. However, I am facing an is ...

Tips for changing the color of MUI TextField in React.JS?

Is there a way to customize the color of the TextField frame? It always shows up as black, making it hard to use in dark mode. I am looking to change the color of both the label and the input line. return ( <div align="center" ...

Invoke a C# instance method from within a static method in Blazor using DotNet.invokeMethodAsync called by JavaScript

Is it possible to invoke a non-static method from a static method in a Blazor application while changing a C# property value from JavaScript using DotNet.invokeMethodAsync? I have the following code working so far: JS File: [script.js] function ChangeCon ...

Utilize various designs on Bootstrap cards

In my Angular 9 project, I'm utilizing Bootstrap 4 cards with NGFOR to dynamically display elements fetched from the database. I have an array containing different styles for the card border, and I want each card to apply a random style from this arr ...

What is the best way to extract data produced by Javascript and parse it with BeautifulSoup?

I am attempting to transfer comments from a blog by utilizing web scraping in Python and BeautifulSoup. The information I need is not present in the HTML itself and appears to have been created within a script tag (which I cannot locate). I have come acros ...

What steps can be taken to fix the error message 'Invalid Element Type'?

I encountered an issue with a customized version of the react-bootstrap navbar component that I saved in a file called navigation.js. Despite exporting and importing it into my main App.js file, I continue to receive the following error: The element type i ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Guide to using jQuery to input a multi-line text into a field

Dealing with a value that spans multiple lines obtained from PHP has been challenging due to the structure of textareas. The standard method of inserting it into the textarea is not feasible in this case. I resorted to using jQuery for this purpose, but ...

Click judiciously on the ng-if directive within AngularJS

HTML : <div ng-app="myApp" ng-controller="someController as Ctrl"> <div class="clickme" ng-repeat="elems in Ctrl.elem" ng-click="Ctrl.click(elems.title)"> {{elems.title}} <span>click me</span> <div id="container"> ...

Determine the RGB color values for specific coordinates within Adobe Illustrator

Currently exploring ExtendScript for JavaScript in Adobe Illustrator 2015. Is there a method to retrieve RGB values based on coordinates within the code below? // initializing document var doc = app.activeDocument; // defining x and y coordinates for colo ...

This function is functional with jquery version 1.4.2 but encounters issues with jquery version 1.9.1

I have encountered an issue with a script that submits data to my database. The script worked perfectly on version 1.4.2, but the template I am using now requires version 1.9.1, so I updated my site accordingly. However, after the update, I am facing an er ...

Expanding the prototype of NodeList

I am utilizing the "html5" node.js library, which is built on top of the "jsdom" library (https://github.com/aredridel/html5) This is my code snippet: var HTML5 = require('/usr/lib/node_modules/html5/lib/html5'), Script = process.binding( ...