user1306732 user1306732 - 3 months ago 7
Javascript Question

JS - How to run something when a function has ended

Here is a code that should open and close my site's menu. The menu is divided to divs and each one is timed to enter the screen after the other.

<script type="text/javascript">
var s=0;
function menuOpen() {
if (s==0){
document.getElementById("menu_icon").src = "x.png";
document.getElementById("nav_menu").style.zIndex = "3";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.remove('loading');
}, index * 100);
});
s++;
} else {
document.getElementById("menu_icon").src = "menu_icon.png";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.add('loading');
}, index * 100);

});
s=0;
// how to make this part run after the menu has finished folding?
setTimeout(function(){
document.getElementById("nav_menu").style.zIndex = "1";
}, 1500);

}

}


</script>


The content of the page is at z-index 2. The menu when folded is at 1 and when open at 3.

Is there a way to run the command moving the menu to z-index 1 after the menu has finished folding completely?

Currently what I did was to time the animation (1600ms) and use setTimeout. But this timing will change if I'll add more lines to my menu or if someone is clicking rapidly on the menu icon.

I'm rather new to JS and Jquery so go easy on me (:

Thanks of your help.

Answer

and with CSS transitions.

var s=0;
                function menuOpen() {
                    if (s==0){
                        document.getElementById("menu_icon").src = "x.png";
                        document.getElementById("nav_menu").style.zIndex = "3";
                        $('.box-wrapper').each(function(index, element) {
                        setTimeout(function(){
                            element.classList.remove('loading');
                        }, index * 100);
                    });
                    s++;

                         $("#last").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
                    document.getElementById("nav_menu").style.zIndex = "3";
                             });

                    } else {
                        document.getElementById("menu_icon").src = "menu_icon.png";
                        $('.box-wrapper').each(function(index, element) {
                        setTimeout(function(){
                            element.classList.add('loading');
                        }, index * 100);

                    });
                        s=0;
                    $("#last").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
                    document.getElementById("nav_menu").style.zIndex = "1";
                   $("#nav_menu").scrollTop(0);

                  });

                    }

                }