Javascript function sequencing when value returned

390 views Asked by At

I have three functions: show(), hide(), and swap() that control the current template displayed in the layout, given the id of the template container element.

I'd like the swap function to call show and when show returns a value, I'd like to trigger the hide function.

E.g.

var hide = function(template) {
    TweenMax.to(frame, 1.18, {
        opacity: 0,

        onComplete: function() {
            return true;
        }
    });
}

var show = function(template) {

}

var swap = function(currentTemplate, targetTemplate) {
    // hide(currentTemplate) then when "true" is returned, show(targetTemplate)

}

swap();

The onComplete function inside TweenMax runs after 1.18 seconds. I know I could put show() inside this or pass show into the hide function, but I'd rather keep the two independent if possible.

Is there a way to do this (preferably w/o jQuery)?

Thanks!!

2

There are 2 answers

0
raorao On

as long as hide and show are synchronous -- which since they both are simple DOM updates, seems likely to be true -- you can use swap for control flow.

That said, if these actions were asynchronous (if they required AJAX requests, for instance) this approach would not work. You would have to pass around callbacks to get them working, or use the new Promise in es6 interface to get things working.

hide(template).then(show)
0
Tahir Ahmed On

Wouldn't TimelineMax suffice? If I understand it correctly, you are looking to sequence your animations and if you already have TweenMax loaded in, you can use TimelineMax for this because TweenMax bundles TimelineMax & other goodies with it.

So, your code can become:

function swap(currentTemplate,targetTemplate){
    new TimelineMax().to(currentTemplate,1.18,{opacity:0}).to(targetTemplate,1.18,{opacity:1});
}

Take a look at this fiddle. Hope you find it useful.

Update:

In this new fiddle, I have added a Toggle button which toggles the animation going back or forward.

Code of which is as belows:

JavaScript:

var byeWorld=document.querySelectorAll('.bye-world')[0];
var helloWorld=document.querySelectorAll('.hello-world')[0];
var toggleButton=document.querySelectorAll('.toggler')[0];
var timeline=new TimelineMax({paused:true,reversed:true});
var duration=.8;

function init(){
    toggleButton.addEventListener('click',swap,false);
    TweenMax.set(helloWorld,{opacity:0});
    timeline.to(byeWorld,duration,{opacity:0,ease:Power2.easeIn}).to(helloWorld,duration,{opacity:1,ease:Power2.easeOut});
}

function swap(){
    (timeline.reversed())?timeline.play():timeline.reverse();
}

init();

Hope it helps.