A Simple Parallax Template Using ScrollMagic And GreenSock

A Simple Parallax Template Using ScrollMagic And GreenSock

In this third template we are introducing GreenSock and a parallax effect on the background images.

What you will learn from this template?

3. A Simple Parallax Template Using ScrollMagic And GreenSock

How to create a parallax effect with ScrollMagic?

VIEW DEMO DOWNLOAD FILES

Is JavaScript too much for you? Try Skrollr first.

It is another very popular scrolling library used on some award winning websites such as redcollar.digital.

How To Create A Parallax Scrolling Website using Skrollr.js will teach you how to create a similar effect using Skrollr.

Now lets create the parallax effect using ScrollMagic and GreenSock.

HTML and CSS

To be able to use GSAP with ScrollMagic we need to include additional plugins.

<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/animation.gsap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.2/plugins/ScrollToPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/debug.addIndicators.min.js"></script>

The Layout for Parallax Effect

In the previous ScrollMagic template we had our background images applied straight to our .slide containers.

For a better performance and a smoother effect, we create a new div.bcg inside of each slide and apply the background images to these containers.

<article id="slide01" class="slide fs">
    <div class="bcg"></div>
    ...
</article>

In the CSS we set the position: absolute and width and height: 100%, to stretch the background containers to full-screen.

.bcg {
    background: no-repeat center center;
    background-size: cover;
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 1;
    .header-container & {
        background-image: url(../img/img_mountains01.jpg);
        background-size: cover;
    }
    #slide01 & {
        background: url(../img/img_mountains02.jpg) no-repeat center center;
        background-size: cover;
    }
    ...
}

Now we use ScrollMagic to change the position of the .bcg on scroll.

ScrollMagic Scenes

Here is a visual breakdown of our multiple ScrollMagic Scenes.

A Simple Parallax Template Using ScrollMagic And GreenSock

For each of the slides we create a new ScrollMagic scene slideParallaxScene and set the triggerHook to be at the bottom of the viewport.

// move bcg container when slide gets into the view
slides.forEach(function (slide, index) {

    var $bcg = $(slide).find('.bcg');

    var slideParallaxScene = new ScrollMagic.Scene({
        triggerElement: slide, 
        triggerHook: 1,
        duration: "100%"
    })
    .setTween(TweenMax.from($bcg, 1, {y: '-40%', autoAlpha: 0.3, ease:Power0.easeNone}))
    .addTo(controller);
});

How to add GreenSock tween to ScrollMagic Scene?

ScrollMagic and GreenSock Tween

The parallax effect is defined in the .setTween() option of the slideParallaxScene ScrollMagic scene.

It contains a simple GreenSock tween of the background container.

TweenMax.from($bcg, 1, {y: '-40%', autoAlpha: 0.3, ease:Power0.easeNone})

When the slide comes into the view, the background container .bcg is 40% up from its original CSS position and is animating to y: 0 over the duration of 100% of the viewport height.

The animation starts when the top of the slide reaches the bottom of the viewport thanks to triggerHook: 1.

You can read more about triggerHooks in SVG Scrolling Animation Triggered By ScrollMagic tutorial.

Is this a first time you hear about GreenSock?

Here is a good place to start – Simple GreenSock Tutorial – Your first steps with GSAP.

How to add GreenSock timeline to ScrollMagic Scene?

ScrollMagic and GreenSock Timeline

The intro animation are multiple tweens combined in a single GreenSock timeline introTl and is triggered when the user starts scrolling down, thanks to the triggerHook: 0.

// move bcg container when intro gets out of the the view
var introTl = new TimelineMax();

introTl
    .to($('#intro header, .scroll-hint'), 0.2, {autoAlpha: 0, ease:Power0.easeNone})
    .to($('#intro .bcg'), 1.4, {y: '20%', ease:Power1.easeOut}, '-=0.2')
    .to($('#intro'), 0.7, {autoAlpha: 0.5, ease:Power0.easeNone}, '-=1.4');

var introScene = new ScrollMagic.Scene({
    triggerElement: '#intro', 
    triggerHook: 0,
    duration: "100%"
})
.setTween(introTl)
.addTo(controller);

We are fading out the text while moving the background container to y: 20%.

In other words the background container is moving 5x slower than the scrolling speed.

How To Create A Smooth In-Page Navigation?

To create a smooth navigation, we overwrite the default “jump” behaviour and animate smoothly to the right position on the page.

// change behaviour of controller to animate scroll instead of jump
controller.scrollTo(function (newpos) {
	TweenMax.to(window, 1, {scrollTo: {y: newpos}, ease:Power1.easeInOut});
});

The easing in the window tween above will define the smoothness of the effect.

Try to change it to ease:Bounce.easeOut and you will see how it affects the experience.

//  bind scroll to anchor links
$(document).on("click", "a[href^='#']", function (e) {
	var id = $(this).attr("href");
	if ($(id).length > 0) {
		e.preventDefault();

		// trigger scroll
		controller.scrollTo(id);

		// if supported by the browser we can even update the URL.
		if (window.history && window.history.pushState) {
			history.pushState("", document.title, id);
		}
	}
});

The on click function takes all the links on the page and triggers our smooth tween defined above.

Read more about Anchor Link Scrolling with ScrollMagic.

Conclusion

There you have it, another template into our collection.

Take it apart, explore the source code and get in touch in the comments if you will have any questions.

Next time we will create A Simple One Page Template with a preloading screen!

Other ScrollMagic and GreenSock Tutorials

Download Free Toolkit

All you need to know to get started with GreenSock and ScrollMagic, in one single package. Straight into your inbox.

100% Privacy. Guaranteed! Powered by Kit

30 thoughts on “A Simple Parallax Template Using ScrollMagic And GreenSock

  1. Patrick Whitty-Clarke

    Hey,

    I’m running Windows 10 and in Chrome and Firefox and I can’t see any parallax or transition effects at all… It does work in IE11 and Edge though

    Reply
      1. Patrick Whitty-Clarke

        Hi Petr,

        Definitely check it out on a touchscreen Windows 10 laptop, I think that might be the reason why it isn’t working for me.

        Reply
  2. Norman Dubois

    Hi Petr,

    i need to have dynamic elements to make a scrolling effect, so I can’t put them in a JavaScript array because they will be produced by wordpress.
    I now tried to get them via jquery but it doesn’t seems to work…
    Do you have an idea?
    Here is my code

    var controller = new ScrollMagic.Controller(),
    	$blogEntries = $('.blog-article');
    
    $blogEntries.each(function(index){
    	var $this  = $(this),
    		blogTL = new TimelineMax(),
    		img = $this.find('.blog-article__image'),
    		headline = $this.find('.blog-article__figcaption'),
    		excerpt = $this.find('.excerpt');
    
    	blogTL
    		.to(img, 1.2, {y : '-50%', ease: Power4.easeOut});
    
    	var blogScene = new ScrollMagic.Scene({
    		triggerElement : $this,
    		offset : 100,
    		duration : '100%',
    	})
    	.setTween(blogTL)
    	.addIndicators()
    	.addTo(controller);
    });
    

    It only makes the animation on the first object. Do you have any ideas?
    It would be nice if you could help!
    Thanks!!

    Reply
  3. Norman Dubois

    Hi,

    i finally solved the problem.
    The trick is to loop 2 times through the items.
    The first loop is to add ids to all your elements and put them into an array:

    So here are my initial variables

    // Variables
    var $boxes = $('.box'),
        $this, $headline, $boxContent, $boxBG, tlBox, 
        controller = new ScrollMagic.Controller(),
        elArray = [];
    

    Now I looped through the items and put them into the array with a jquery each loop

    // Adding the ids
    $boxes.each(function(index){
        $(this).attr('id', 'blogID' + index);
        var id = '#blogID' + index;
        elArray.push(id);
    });
    

    Now I have an array with strings of the ids and every element has a id which I can use for the triggerElement.
    I can now use this array to loop over it like Petr explained in the tutorial:

    // Loop through the items
    elArray.forEach(function(element, index){
        var tween = new TimelineMax(),
        bg = $(element).find('.box__bg'),
        headline = $(element).find('.box__content h2');
    
        tween
            .from(bg, 0.5, {y: '50%', backgroundColor: 'red', ease: Power4.easeOut})
            .from(headline, 0.5, {y: '10%', ease: Power4.easeOut});
    
        var scene = new ScrollMagic.Scene({
            triggerElement : element,
            triggerHook : 'onCenter',
            duration: '100%',
        })
        .setTween(tween)
        .addIndicators()
        .addTo(controller);
    })
    

    I don’t know if there is a better way to solve it but I hope that it could help some people who are having the same problem than me! 🙂

    Thanks a lot Petr for this great tutorial!

    Reply
  4. Patrick Mullady

    Hi Petr, I was checking this demo on Windows 8 latest Chrome/FF and the animations don’t fire. The site simply scrolls only.
    The animations DO work on IE11 however…go figure.

    I saw someone else had this issue previously on W10…any ideas on this?

    https://ihatetomatoes.net/demos/scrollmagic-templates/scrollmagic-template-03/

    Your site is great! Thanks
    – Patrick

    Reply
      1. Patrick Mullady

        Thanks Petr.
        I did a test via CrossBrowserTesting.com on my machine specs and it does work fine.
        My testing PC browsers need to be reinstalled.. Sorry to bother you with that

        Last 2 things:
        1. I noticed that on iOS 9 on my iPad the scroll animation and text animations don’t trigger. I did read in the ScrollMagic docs that it supports mobile but I suspect there are certain major pitfalls on Mobile for scrolling with animation as it relates to performance.
        In your JS comments I saw //Enable ScrollMagic only for desktop//
        Can you offer any more info on why you chose to disable mobile? 🙂

        2. Are your ScrollMaster/Parallax classes using ScrollMagic or only Skrollr? I am tempted to buy them but I am concerned about how relevant they still are since Skrollr is no longer being updated/developed. ScrollMagic has MUCH better documentation and the Git seems healthy.

        You’re Greensock SVG was really excellent so part of me thinks that I could still learn a bit from the Skrollr course even if its outdated….but I was hoping to get your honest opinion since ScrollMagic seems to be the more appropriate library for me.

        Thanks Petr!
        – Patrick

        ps – I made this video if you are interested https://youtu.be/gnVY8euA7yU
        But like I said after testing the demo site on CrossBrowserTesting.com with the same browser specs. It seems to be an extremely isolated issue with my browsers on Windows 8.1 😉

        Reply
        1. Petr Tichy Post author

          Hi Patrick, thanks for the nice words about the GreenSock Workshop. Here are my answers to your questions.

          #1 – Scrolling Animations on mobile

          I know ScrollMagic and even Skrollr can work on mobile, but the performance even if you spend some time optimizing it, will never be the same as a natural scrolling on the touch devices. In most cases scrolling animations are adding a bit of story telling or revealing on desktops, but I feel this effect is mostly lost and ineffective on mobile devices. That’s why my suggested approach is and always was to turn scrolling animations off for mobile devices.

          #2 – Parallax Scrolling Master Class

          This online course is purely focused on Skrollr and doesn’t cover any ScrollMagic. You are right that Skrollr is not being developed anymore, but that said it still works perfectly fine in all modern browsers and is a perfect solution especially for designers and developer not comfortable with learning and coding with JavaScript or jQuery.

          I am currently putting together an outline for a brand new ScrollMagic course, that might be more relevant to you than PSM.

          Thanks a lot for the video, but I couldn’t see any JavaScript errors related to the main.js though 🙁 Have you tried to download the files and run them locally in the same browsers?

          Reply
  5. Patrick Mullady

    Thx for the mobile explanation. I figured as much.

    I did download the files. Same results. I reinstalled my browsers and everything works. There must’ve been plugins/extensions causing issues. Fun stuff.

    Looking forward to the ScrollMagic course!
    Thx Petr

    Reply
    1. Petr Tichy Post author

      I am glad to hear that it is now working fine for you. What are your biggest frustrations about ScrollMagic and the workflow? Or have you seen any effects or layouts that you would like to see covered in the course? Let me know. Thanks Patrick!

      Reply
      1. Patrick Mullady

        I am only starting to research Scroll Magic for a prototype I am building. Client wants “a scrolling parallax site”…typical request these days.
        When I searched for parallax scrolling your demos bubble up quickly.
        My first point was to check the demos on browsers to be sure it works where we need it to work.
        I admire your coding style very much. It’s incredibly well organized. Thanks for caring like i do. 🙂

        I’ll be playing with ScrollMagic more today so I will definitely report back with my stumbling blocks. What I can say is I enjoyed your simple examples like scrollmagic-template-02 and scrollmagic-template-03. They are simple and straight forward. Perfect.
        I use CodeKit so the added bonus of compiling is awesome.

        Do you have an ETA on your course? I’ll be looking for that.
        Talk soon
        Thanks!
        – Patrick

        Reply
        1. Petr Tichy Post author

          Hi Patrick, no ETA on the ScrollMagic course yet, I am putting together all the material at the moment and sorting out through all the ScrollMagic questions I am getting. If there is an effect or animation you would want to be covered let me know (links are great). Thanks

          Reply
  6. kian

    Hello Petr,

    i am using a touch screen laptop (asus s400c) and the demo seems to be not working; there is no animation.

    did some debugging and found out “Modernizr.touch” is returning true (inside main.js) thus scrollmagic is not trigger.

    was wondering in such case whats the “best” solution.

    thanks and article well written!

    Reply
    1. Petr Tichy Post author

      Hi Kian, thanks for checking it out.

      There is an if statement in the main.js:

      // Enable ScrollMagic only for desktop, disable on touch and mobile devices
      if (!Modernizr.touch) {
      
          // enable scrollmagic
      
      }
      

      The exclamation mark before the Modernizr.touch means that the code inside is only executed when the touch is not detected.

      Seems to be working fine though.

      Reply
      1. Patrick Whitty-Clarke

        Shouldn’t you combine the check with a device width check or something? Otherwise all Windows 10 laptops with touch support won’t run the demo.

        Reply
  7. Duncan

    Hello, I appear to be having the same problem as others here. It seems my parallax effects with sometimes (but only in debugging mode with the triggers on, or if i manually scroll with the sidebar but again rarely working, just scrolling as normal)

    Any solutions to this yet?

    Reply
  8. Andrew Staroscik

    Hi Petr,

    you should indicate somewhere in the demos that they are disabled on touch detection. People discovering your site while web surfing on mobile devices can’t be getting a good impression.

    Reply
  9. unaligned

    I was wondering if there was a way for the backgrounds in the slides to also scroll. I tried messing with the code but I couldn’t make it happen.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.