1

When I first click on the #menuIcon div I want it to animate the #menu div left: 0em and then when I click on it a second time animate #menu to left: -12em.

The first part works but when I click again nothing happens. #menuIcon is a child of #menu, does this affect anything?

Here's my JS (adapted from this question, the micro query plugin answer):

$(document).ready(function(){

    jQuery.fn.clickToggle = function(a,b) {
        function cb(){
            [b,a][this._tog^=1].call(this);
        }
        return this.on("click", cb);
    };

    $("#menuIcon").clickToggle(function() {   
        $("#menu").animate({left: "0em"}, 500);
    }, function() {
        $("#menu").animate({left: "-12em"}, 500);
    });
});

Thanks in advance.

As suggested by John S here's the relevant(I think) html:

<div id="menu">

    <div id="menuIcon">
        <div id="menuIcon1"></div>
        <div id="menuIcon2"></div>
        <div id="menuIcon3"></div>
    </div>

</div>

And css:

#menu {
    width: 16em;
    height: calc(100% - 5em);
    background-color: blue;
    position: fixed;
    bottom: 0;
    left: -12em;
}

#menuIcon {
    height: 4em;
    width: 4em;
    position: relative;
    top: 0;
    left: 12em;
    background-color: green;
}
Community
  • 1
  • 1
cCe.jbc
  • 107
  • 1
  • 9

3 Answers3

1

Might be easier just use an added class to toggle the direction:

$("#menuIcon").on("click", function() {  
     $this = $(this)

     if(!$this.hasClass("open"))
     {
         $("#menu").animate({left: "0em"}, 500);
         $this.addClass("open");
     }
     else
     {
        $("#menu").animate({left: "-12em"}, 500);
        $this.removeClass("open");
     }
 })

This isnt as clever as what you were trying but I think its a lot easier to read, and should work

labago
  • 1,338
  • 2
  • 12
  • 28
0
$('#menuIcon').toggle(
  function(){
   $("#menu").animate({left: "0em"}, 500);
  } , 
  function(){
   $("#menu").animate({left: "-12em"}, 500);
  }
);

Use the Jquery toggle function and will do the magic for you. Thanks

Fakhir Shad
  • 1,071
  • 8
  • 20
  • That version of the [JQuery `toggle()` function](https://api.jquery.com/toggle-event/) was deprecated in v1.8 and removed in v1.9, so you would have to be including an old version of JQuery to use it. – John S Jul 02 '16 at 17:39
0

As John S said, my problem was not with the jQuery but with the rest of my HTML.

I had a div with that overlapped #menu when it was opened. I set #menu 's z-index to 2 and that worked.

cCe.jbc
  • 107
  • 1
  • 9