totallygloria totallygloria - 3 months ago 20
CSS Question

Debugging callback functions in Javascript: second function isn't reached

I'm writing a website in vanilla javascript (can't use JQuery), where I've written a little fadeOut function with javascript and CSS. I'd like for the fadeOut to finish before the next function is called. To do this, I'm trying to use a callback function -- the only purpose of the function is to ensure the first function completes before the second is called. I've read several tutorials, but can't figure out what I'm doing wrong -- I never arrive at the second function:

function mformSubmit() {
doCallback(fadeOut, function() { setupM });
}

function fadeOut () {
for(var i=0; i<m_types.length; i++) {
if (document.getElementById(m_types[i]).className != 'selected') {
document.getElementById(m_types[i]).style.opacity = 0;
} else {
selection = m_types[i]; }
};
}

function doCallback(callback) {
if (typeof callback === "function") {
callback();
}
}

function setupM() {
alert("I arrived in the setup function");
}


And the relevant CSS bits:

label.unselected {
background-color: #fff;
float: left;
padding: 5px;
border: 2px solid #CCC;
border-radius: 8px;
box-shadow: rgba(0,0,0,0.04) 15px 15px;
margin: 10px 10px 20px 30px;
/* Opacity tricks */
-webkit-transition: opacity 800ms ease;
-moz-transition: opacity 800ms ease;
-o-transition: opacity 800ms ease;
transition: opacity 800ms ease;
}


Thanks in advance!

Answer

doCallback(callback), it's clear that it accepts one argument callback. Here's the fix which still won't work.

function doCallback(mainFn, callback) {
    if (typeof mainFn === "function") {
        mainFn();
    }        
    if (typeof callback === "function") {
        callback();
    }
}

The correct way is to set the callback on fadeOut(), and you don't need to nest you functions.

function fadeOut (callback) {
    for(var i=0; i<m_types.length; i++) {
        if (document.getElementById(m_types[i]).className != 'selected') {
           document.getElementById(m_types[i]).style.opacity = 0;
        } else {
            selection = m_types[i]; }
       };
    // check if callback is function 
    if(typeof callback == 'function') callback();
}

And call it like:

fadeOut(function(){
   // code;
});

// or 

fadeOut(setupM); // note you don't need to pass ()