Search code examples
javascriptjqueryparallaxgsapscrollmagic

Using links within a parallax ScrollMagic site


I'm making a vertical parallax scrolling site with ScrollMagic which includes a navigation menu at the top to link within the site.

The menu itself works correctly when no parallax animation is applied to the scroll but when the parallax is added (ie the 2nd section moves up over the intro section), it seems unable to take the reduction in overall height into account when moving to the section, so it overshoots.

Here is some code:

var site = {
    smController : {},

    init : function () {
        site.setupScroll();
        site.setupMainNavigation();
        site.setupAnimation();
    },

    setupScroll : function () {
        // init the smController
        var controller = new ScrollMagic({
            globalSceneOptions: {
                triggerHook: "onLeave"
            }
        });

        site.smController = controller;
    },

    setupMainNavigation : function () {
        $('.menuclick').on('click', function (event) {
            event.preventDefault();
            var anchor = $(this),
                sectionId = $(anchor.attr('href'));

            site.scrollToSection(sectionId);
        });
    },

    /**
     * uses tweenlite and scrolltoplugin from greensock
     * @param  {string} sectionId id of section to scroll to
     * @return {void}
     */
    scrollToSection : function (sectionId) {
            var scrollYPos = $(sectionId).offset().top;

            TweenLite.to(window, 0.5, { scrollTo:{ y: scrollYPos } });
    },

    setupAnimation : function () {
        // parallax animation - move marginTop back by 100%
        var tween = new TimelineMax()
                .to('#section1', 2, { marginTop: '-100%', ease:Linear.easeNone });

        var controller = site.smController,
            scene = new ScrollScene({ duration: 500 })
                .setTween(tween)
                .addTo(controller);

        // show indicators (requires debug extension)
        scene.addIndicators();
    }
};

$(document).ready(function () {
    site.init();
});

Does anyone have a strategy to deal with moving (parallax) sections like this please?

Thanks


Solution

  • In ScrollMagic 1.1 you can now provide custom scroll functions AND scroll to the beginning of a specific scene.
    Read more here: http://janpaepke.github.io/ScrollMagic/docs/ScrollMagic.html#scrollTo

    I would also strongly suggest not to use animated elements as scroll targets, because their position might be different before and after initiating scroll.
    If you have elements that influence the DOM height, try to take them out of the DOM flow.
    You can do this for example by adding an element as a placeholder and setting your element as positioned absolutely.

    hope this helps.
    J