Coder Social home page Coder Social logo

react-animate-on-scroll's Introduction

Travis

React Animate On Scroll

React component to animate elements on scroll with animate.css. Inspired by React-Scroll-Effect

Install:

npm install react-animate-on-scroll --save

If you want to use the animations from animate.css, be sure to include animate.css in someway in your project This can be done in a number of ways, eg:

npm install --save animate.css

and then importing in your project:

import "animate.css/animate.compat.css"

Or by simply including a link to the file hosted by CDNJS:

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>

Most Simple Use:

import ScrollAnimation from 'react-animate-on-scroll';
<ScrollAnimation animateIn="fadeIn">
  Some Text
</ScrollAnimation>

Properties:

offset - default 150

The "viewport" is by default 150 pixels from the top and bottom of the screen. When part of an element is within the "viewport", animateIn is triggered. When no part of the element is in the "viewport", animateOut is triggered. This size of the "viewport" can be overridden by setting the offset property.

animateIn

Any css animation defined against a class, be it from animate.css or an animation that you have created yourself. The Animation triggers when the element enters the "viewport" (see offset property for more details on this).

animateOut

Any css animation defined against a class, be it from animate.css or an animation that you have created yourself. The Animation triggers when the element is leaving the "viewport" (see offset property for more details on this).

duration - default 1

Animation duration in seconds.

initiallyVisible - default false

Whether the element should be visible to begin with or not.

delay - default 0

How long to delay the animation for (in milliseconds) once it enters or leaves the view.

animateOnce - default false

Whether the element should only animate once or not.

style - default {}

A style object can be assigned to any ScrollAnimation component and will be passed to the rendered dom element. Its probably best to avoid manually setting animationDuration or opacity as the component will modify those attributes.

scrollableParentSelector

By default the code checks to see if the element is visible within the window. This can be changed to any other parent element of the ScrollAnimation by adding a css selector pointing to the parent that you wish to use.

afterAnimatedIn

Callback function to run once the animateIn animation has completed. Receives the visibility of the element at time of execution. Example:

function(visible) {
  if (visible.inViewport) {
    // Part of the element is in the viewport (the area defined by the offset property)
  } else if (visible.onScreen) {
    // Part of the element is visible on the screen
  } else {
    // Element is no longer visible
  }
}

afterAnimatedOut

Callback function to run once the animateOut animation has completed. Receives the visibility of the element at time of execution. Example:

function(visible) {
  if (visible.inViewport) {
    // Part of the element is in the viewport (the area defined by the offset property)
  } else if (visible.onScreen) {
    // Part of the element is visible on the screen
  } else {
    // Element is no longer visible
  }
}

animatePreScroll - default true

By default if a ScrollAnimation is in view as soon as a page loads, then the animation will begin. If you don't want the animation to being until the user scrolls, then set this to false.

Changes:

Version 2.1.0

  • Can now use scrollableParentSelector to use ScrollAnimation within any scrolling parent element.

Version 2.0.2

  • ScrollAnimation components now accept style prop.

Version 2.0.1

  • animateOnce now works properly.

Version 2.0.0

  • The "visible" object passed to the afterAnimatedIn and afterAnimatedOut callbacks has the properties "onScreen" which is true if the element is on the screen, and "inViewport", which is true if the element is in the viewport. visible.completely and visible.partially will no longer work.
  • Should now work on mobile devices.
  • Should work more consistently with dynamically sized elements (eg, images).
  • Elements now "animateIn" when any part of them is in the viewport, not only when they are fully contained in the viewport.
  • The viewport now has a default offset of 150px from the top and bottom of the screen, rather than 100px.

Development:

In the project root:

Install Dependencies:

npm install

Run Tests:

There are some automated test cases with karma and a Chrome headless browser. I attempted to use Jest, and then to use PhantomJS, but could get neither to work with scroll events. To run them:

npm test

Build the component:

gulp build

Run the Demo project:

cd demo
npm install
npm install ..
npm start

react-animate-on-scroll's People

Contributors

adampflug avatar aumirza avatar code47x avatar dbramwell avatar felipeleusin avatar hansyulian avatar hawkins avatar henriqueinonhe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-animate-on-scroll's Issues

Animations aren't coming in when programatically scrolling

hi there, hope theres still some support for this! When Im using any programatical approach to scroll, fore example window.scrollTo( 0, 0 ); , none of the animations are triggered, I need to touch to scroll to trigger the animations, I guess wrong event listener?

Could you please have a look?

thanks!

Call back?

This plugin is amazing! Thank you so much for making it. Sometimes I need to setup a GSAP timeline with staggered animations etc. Is there any way you can add a simple call back event that fires once so I can run my timeline for more complex animations?

Cannot read property 'clientHeight' of null

In development and/or production, ScrollAnimation works as expected, however, when I was running a component test on a component that contained ScrollAnimation, I got an error

console.warn node_modules/react-animate-on-scroll/dist/scrollAnimation.min.js:142
    Cannot find element by locator: undefined
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6820
    The above error occurred in the <ScrollAnimation> component:
        in ScrollAnimation (at Hero.jsx:103)

TypeError: Cannot read property 'clientHeight' of null

      at ScrollAnimation.getVisibility (node_modules/react-animate-on-scroll/dist/scrollAnimation.min.js:127:50)
      at ScrollAnimation.handleScroll (node_modules/react-animate-on-scroll/dist/scrollAnimation.min.js:229:31)
      at ScrollAnimation.componentDidMount (node_modules/react-animate-on-scroll/dist/scrollAnimation.min.js:145:16)
      at commitLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6955:22)
      at commitAllLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8164:7)
      at Object.invokeGuardedCallbackImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2193:10)
      at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2363:31)
      at commitRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8334:7)
      at completeRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9699:3)
      at performWorkOnRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9627:9)

This is the content (summarized) of the Hero.jsx file

export default class Hero extends React.Component {
        render() {
		return (
			<section className="hero" style={{ backgroundImage }}>
                <div className="grid pad-grid">
                    <h1>{translate(locale, this.keys.HEADER)}</h1>
                    <p className="subheader">{translate(locale, this.keys.SUBHEADER)}</p>

                    <a href={bg.path} className="image-author">
                        <i className="fa fa-camera" />
                        <span>{bg.person}</span>
                    </a>

                    <ScrollAnimation animateIn="fadeInLeft" duration={0.2} animateOnce>
                        {this.renderSubForm()}
                    </ScrollAnimation>
                </div>
            </section>
    	)
    }
}

Can anyone help out on how to resolve this error

Scroll animations not working in IE.

I have tried implementing this library in my project and facing issues with internet explorer. I looked at the code and it is using scrollY which is not supported by i.e . Can you please take a look at it and update scrollY to pageYOffset as it is better for cross browser compatibility.

I have modified it from scrollY to pageYOffset

if you want to implement this I can give PR

Thanks

Scroll not working: TypeError: Cannot read property 'pageYOffset' of null

scrollableParentSelector not working

when attempting to execute code as shown on your site's example of scrollableParentSelector

<ScrollAnimation animateIn='fadeIn'
  animateOut='fadeOut'
  scrollableParentSelector='#scrolly-div'>
  <h1>
    scrollableParentSelector
  </h1>
</ScrollAnimation>

scrollableParentSelector='#scrolly-div'> raises error
TypeError: Cannot read property 'pageYOffset' of null

ScrollAnimation.getScrollPos

138 | }, {
139 | key: "getScrollPos",
140 | value: function getScrollPos() {
141 | if (this.scrollableParent.pageYOffset !== undefined) {
142 | return this.scrollableParent.pageYOffset;
143 | }
144 |

unsure how to proceed, please advise

Animations not firing if body and html scroll bar hidden ?

Would it be possible that the animations are not firing because it listens to the html/body scroll bar only ? If so, would it be possible to add our own css tag as a parameter to the component ? (So that it listens to its scroll bar and no more to the html/body one)

Horizontal scroll support?

Was trying to use in an horizontal scroll, when I decided to see the source code, and I saw the inViewport condition is only checking the Y position. Are there any plans on supporting horizontal scroll? Thanks

Possible Added Functionality

So I'm using the animateOnce property to have my Titles animate in, however I also had an afterAnimateIn on it as well. I'm using this so that if a user scrolls down to this title, it annimates in and highlights the proper navigation tab in my site.

<ScrollAnimation animateIn="fadeIn" animateOnce duration={0.5} offset={0} afterAnimatedIn={() => this.props.changeSelectedNav('Skills')}>

My problem here is now that animateOnce works, afterAnimatedIn only triggers after it animates the first time (as it should). However I need this function to run every time the dom element enters the viewport.

Would it be possible to add a function, something like, onEnteredView() that would be called every-time the element enters the viewport, regardless of whether its animated?

Not working in modals

The animations are not triggered in modals. Probably because of the scroll event working only on the parent.
When I enter window.scrollTo( 0, 0 ) in the console it fires the animations.

React.createElement: type is invalid

I do not know if this is issue with react-animate-on-scroll or with my environment.

Full error message:
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

import declaration:
import ScrollAnimation from 'react-animate-on-scroll';

Installed package versions:

TypeScript 2.9.2
@types/react-animate-on-scroll: "^2.1.0
react-animate-on-scroll": "^2.1.5

Bundling (webpack with laravel mix wrapper):
laravel-mix: ^2.1.11

If I change the following lines the error disappears and the component works like a charm but I don't know why:

//exports["default"] = ScrollAnimation;
exports.default = ScrollAnimation;

//module.exports = exports["default"];

Does anybody know what's going here?

Animate once

The animation is triggered once the item in view perfectly and when its out of view it disappears,
Scrolling up brings that back again.

I have modified it by adding an 2 more boolean attributes
animateOnce
isAnimationFinished

if you want to implement that functionality I can PR

thanks

Animations do not load on rapid scroll-down in window

So this is an issue I discovered on testing edge cases for one of my web projects. The ScrollAnimation in question is about 2k pixels down the window and out of the initial page load view. However when the page loads and the user immediately scrolls down at least 1k-2k pixels, the animation does not render. When the user scrolls back up and down again, the animation only seems to render partially.

The code below where this.state.offset = 100:

<ScrollAnimation offset = {this.state.offset} animateIn='pulse'     animateOnce={true}>
   <img className = "HeadlineSponsor" src = {Logo_MEF} ></img>
</ScrollAnimation>

I suspect the issue might lie within loading a large number of ScrollAnimations at the same time, the isvisible() function seems good and window.pageYOffset also works fine.

animatedOut not working

<ScrollAnimation animateOut="animate__flipOutY" animateIn="animate__flipInY" scrollableParentSelector='#root' duration={5} >
    <h1>Some Text</h1>
</ScrollAnimation>

When I scroll the text out of the viewport, the state of the component doesn't change!
Why is that happening?

Don't call animation until user scrolls?

Great package.

Is there a way to not fire an animation until the user has scrolled? I have a hero that animates on page load (not using the ScrollAnimation component) and then sections below that that are typically "below the fold" that use ScrollAnimation. However on some larger and hi-res screens those secondary sections are in the viewport on page load and thus kick off the CSS animation tied to that ScrollAnimation component. I'm wondering if there's a way to ensure those don't kick off until the user has actually scrolled.

Thanks.

React router - on navigate back 1 page and scroll up animations dont work

First of all thanks for the library, very helpful! To my issue - I have just found a bug.

On my page I have 9 projects that appear as I scroll down, works perfect. Except for if I am at the bottom of the page, when I navigate to another page and then click the browser back button, the animation for any projects in my viewport (bottom of the page) will appear, but as I scroll back up my other projects, they do not appear. It appears that the viewport checker is not picking up that there are projects in view when scrolling up after having navigated back to that page.

Just to note that if I am at the bottom of a page and reload, then scroll up everything works perfectly as it should. It is only if I am at the bottom of a page, then navigation to another and click back to get to my projects page, and then scroll up that new projects in my viewport remain hidden.

Would you know why this might be? Thanks!

React 17.0 Not Supported

The library is no longer supported in the latest version of React.

react@">= 15.4.1 < 17.0.0-0" from [email protected]

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"17.0.1" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@">= 15.4.1 < 17.0.0-0" from [email protected]
npm ERR! node_modules/react-animate-on-scroll
npm ERR!   react-animate-on-scroll@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 

Customize Animation Easing

Hello. I'm loving this package so far. We switched from react-spark-scroll and the performance/ease of use is night and day.

It would be a great enhancement to allow the developer to choose a custom easing function. I believe that one could currently use the style attribute in React to set animationTimingFunction like so:

style={{ animationTimingFunction: ease-in-out }}

This works fine, but adding an easing attribute would be an easy enhancement. It would something like this:

easing="ease-in-out"

onComplete fires too early

Great plugin, callback works great when the component slides into view normally, however it seems to be triggered by the component entering the viewport rather than when the animation has actually finished

It looks like this condition on line 97 allows it to fire when not completely visible
return visible.partially && !visible.completely

In the example, if you scroll down slowly the alert fires as the component enters the viewport - see screenshot

image

Child elements disappear on real device(iPhone 7)

When scrolling the element initially animate into view on scroll. but after they disappears.

It is working on the chrome editor properly but on a real device the problem occurs. Very strange. No console logs are printed with any errors.

Not work on any component

I am trying to add landing page, but it does not work only if I configure the offset less than 50 I have tried it in different components and it does not work.
This is a fragment of my code: the FirstSection component is large but ScrollAnimation is not displayed when scrolling

PS. Sorry for my english.

  <ReactCSSTransitionGroup
    transitionName="section"
    transitionAppear={true}
    transitionAppearTimeout={500}
    transitionEnter={false}
    transitionLeave={false}>

    <FirstSection currentUser={currentUser}/>
    
    <ScrollAnimation animateIn="fadeInLeft">
      Hola
    </ScrollAnimation>

  </ReactCSSTransitionGroup>

Inline display

It would be nice if we could specify if it is inline or not.
Right now the main element is a <div>... so it is always display: block.
I might just create a PR later if I feel less lazy later.

[Request]: Dynamic Element Type (div)

It would be useful if we could specify the element that's created because if we want to, for example, animate something inside a paragraph it creates a

and div's are not allowed inside paragraphs

image

A proof of concept would be the react-intl FormattedMessage component, have a look at the tagName property
https://github.com/formatjs/react-intl/blob/master/docs/Components.md#formattedmessage

usage would be something like this;

<p>
    My fancy paragraph 
    <ScrollAnimation animateIn="jackInTheBox" tagName="span">can animate</ScrollAnimation>
</p>

Animations not working well on phones

Hello,
First of all, thank you for this nice component !
However, sometimes, animations are a bit laggy on phones. It would be great to have a props where you could specify a break point (ex : 1024) where the animations would not load.
Or maybe a boolean like (animateOnPhone = {false})
Thank you !

Apply animate.css update

I found that the library is still using older version of animate.css. I would like to add newer version support here.

How do I use this with Styled Component?

Hi, I'm trying to use animate on scroll with styled component.

Here is my styled component keyframe animation:

export const flipUp = keyframes`
  from {
    transform: rotateX(-85deg);
  }
  to {
    transform: rotateX(0deg);
  }
`;

And then I try to import that flipUp and apply into the ScrollAnimation:

<ScrollAnimation animateIn={flipUp}>
	<div>Hello</div>
</ScrollAnimation>

But it didn't animate at all. I guess I'm doing it wrong way, do you have any idea how to get this works? Thanks!

New features request

Hi there, would be great to implement features below:

a) Don't run animation when elements above of viewport.

Details: For example when we use a browser back button scroll position saved on a previous page and we are at the middle of the page. When we scrolling to top animation is running. I think it should be optional because it leads to some misunderstanding from users. We should add an option to run animations only by scrolling down the site.

b) Add sort of beforeAnimatedIn.

This will add more control for animation behaviour. For example prevent animation on some statement.

Thanks!

have item stick around after having faded in

Great project - we were just using the simple example for fadein, is there a way to have an item stick around after it has faded in once, i.e. not have it disappear once we scroll away from it again?

Make animate.css optional

Animate.css is nice, but in my use case and I think many other cases we have our own custom animations and all those animations in animate.css are not likely to be used.

besides I had problems with the minified

 (function (exports, require, module, __filename, __dirname) { @charset "UTF-8";
                                                              ^
SyntaxError: Unexpected token ILLEGAL 

Thats why I forked and using a custom version of react-animate-on-scroll.

Thanks

Typescript Type Definitions Outdated

When using typescript, the following properties cause errors because they are not included in the type definitions:

  • afterAnimatedIn
  • afterAnimatedOut
  • animatePreScroll

Components not visible

Attempted to do a simple test:

import React from 'react';
import ScrollAnimation from 'react-animate-on-scroll';
import "animate.css/animate.min.css";

const App = () => {
    return (
		<div>
			<ScrollAnimation animateIn='fadeIn'>
				<h1>animateIn</h1>
			</ScrollAnimation>
		</div>
    )
  }

export default App;

But the component isn't showing up on the page on scroll. Element is in the DOM but animation is not getting triggered. Only thing I see in the console is: "[HMR] Waiting for update signal from WDS..."

Any ideas?

I live in a van and work on a hacked chromebook so can't test in IE

I recently released version 2.0.0 which seems to work on mobile chrome, a few versions of desktop chrome and firefox, but I am unable to test in IE currently. If anyone reads this and can confirm whether or not the animations on the demo page work correctly in IE I'd be very appreciative.

The code samples on the demo page used to display incorrectly but the animations worked. Hopefully the current state is the same or better.

Change state of Progress Bar afterAnimateIn

How to use the inVisible in this code to change the state of the Progress Bar to animate after the animation is complete?

I'm using react-animate-on-scroll package to animate my page and in this page I have some Progress Bar.

I would like to animate the progress bar after the scroll animation finished.

For example:

The progress bar will animate from the left side and after reach the position on the screen, then will change the width of the bar till the value assigned.

So far, my code looks like this:

[(https://stackoverflow.com/questions/64393319/change-progress-value-afteranimatedin)]

I'm not sure how to change the state of the progress bar inside the function afterAnimatedIn.

React-animate-on-scroll gives the option, but I'm not sure how to implement it.

Any help will be appreciated.

Animations not working

import ScrollAnimation from "react-animate-on-scroll";
import "animate.css/animate.min.css"

The element is initially invisible as expected but then when it gets in viewport it appears instantly no animation happens tried with different durations

Warning: called setState on unmounted component

I keep getting this error in the console anytime I change Routes in my app:
// proxyConsole.js:56 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ScrollAnimation component. //

Visbility problem

Hi,
I wonder what could be the issue. On some mobile resolutions, the fade in animation seems to work not properly for me, all the elements are set to visibility: hidden when I use the scroll even once and it's not changing since then. What could be the problem? Cheers

Does not seem to work with absolutely positioned items

Great library!

Running into an issue where I wrap an absolutely positioned element. It doesn't animate and the container seems to have no height / width.

Is this a known issue?

CSS for my object:

width: 123px; height: 206px; position: absolute; bottom: 0; right: 0;

How to remove viewport from top?

Hi.
Does anyone know how to disable the viewport from the top? I would like to use it only when I scroll down.

Thanks for help :)

Only makes my block disappear ... and does nothing else ...

<ScrollAnimation animateIn="fadeIn">
   <GridImageBlock
      imageLink="/static/images/after.png"
      caption="↑ Data Usage	↓ Analysis Time	↑ Accuracy"
      details="Lorem ipsum dolor, sit amet consectetur adipisicing elit.
      Molestias dolores quia sit harum accusamus quaerat repudiandae.
      Facere amet, non pariatur qui voluptate, at nam molestiae
      sapiente, ipsa quasi minus est."
      />
</ScrollAnimation>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.