Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a toggle command faster when something is visible?

Tags:

jquery

toggle

My aim is to run something faster once the user can see it. To explain, once the user clicks the menu button it will open, which is fine but when the user clicks to close the menu, it should close the menu down faster. However my code does not want to fire the second 'else if' part of my code.

Here my code :

  $(document).ready( function() {                       
   if ( !$(".TopList1").is(":visible")  ) { 
    $('.MenuButton').click(function() {         
        $( ".TopList1" ).toggle("slide", {direction: "down"}, 1000);
        $( ".TopList2" ).delay(800).toggle("slide", {direction: "down"}, 800);
        $( ".LeftList1" ).toggle("slide", {direction: "left"}, 1000);
        $( ".LeftList2" ).delay(800).toggle("slide", {direction: "left"}, 1000);
    });
   } else if ( $(".TopList1").is(":visible")  )  {
    $('.MenuButton').click(function() {         
        $( ".TopList1" ).toggle("slide", {direction: "down"}, 800);
        $( ".TopList2" ).toggle("slide", {direction: "down"}, 800);
        $( ".LeftList1" ).toggle("slide", {direction: "left"}, 800);
        $( ".LeftList2" ).toggle("slide", {direction: "left"}, 800);
    });
   }
});

Update:

Heres the jsFiddle link, the css is not right on there but you can get the idea, the links open up but i want them to close at all the same time! - The end result might not even toggle the close but just fade out!

like image 517
Glenn Curtis Avatar asked Nov 12 '22 05:11

Glenn Curtis


1 Answers

The issue was that your if statement was only being checked on initial load. As it evaluates to true, only the top half of your code was being triggered. The reason it works at all is because toggle is smart, so the top half both expands and collapses the submenus.

This code works:

$(document).ready( function() {
    var menuClosed = true;
    $('.MenuButton').click(function() {
        if (menuClosed) {
            menuClosed = false;
            $( ".TopList1" ).toggle("slide", {direction: "down"}, 1000);
            $( ".TopList2" ).delay(800).toggle("slide", {direction: "down"}, 800);
            $( ".LeftList1" ).toggle("slide", {direction: "left"}, 1000);
            $( ".LeftList2" ).delay(800).toggle("slide", {direction: "left"}, 1000);
        } else {
            menuClosed = true;
            $( ".TopList1" ).toggle(0);
            $( ".TopList2" ).toggle(0);
            $( ".LeftList1" ).toggle(0);
            $( ".LeftList2" ).toggle(0);
        }
    });
});
like image 85
Evan Hammer Avatar answered Nov 15 '22 07:11

Evan Hammer