简体   繁体   中英

Function only runs once

I made this little jQuery function to make my navigation slide out on mobile devices. My only problem though... I can only show and hide it once... Can anyone help me out with this? Thanks in advance!

$('#menu-btn').click(function(){

  if ($('nav ul').css('margin') == '83px 0px 0px -225px') {

    $('nav ul').animate({
      margin:'83px 0px 0px 0px'
    }, 200);

  }
  else {

    $('nav ul').animate({
      margin:'83px 0px 0px -255px'
    }, 200);

  }

});

As alternative solution you can follow this way:

You may toggle class with margins on every click instead string compare

$('#menu-btn').click(function() {
    $('nav ul').toggleClass('slided')    
})

Also you need 2 CSS rules

nav ul {
    margin: 83px 0px 0px 0px
}

nav ul.slided {
    margin: 83px 0px 0px -225px
}

 var flag=true; $(function(){ $('#menu-btn').click(function(){ var newMargin = flag===true ? '83px 0px 0px -225px' : '83px 0px 0px 0px'; $('nav ul').animate({ margin: newMargin // toggle margin according to flag }, 200); flag = !flag;//toggle flag }); }); 
 nav ul { margin: 83px 0px 0px 0px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav> <ul> <li>List 1</li> <li>List 2</li> <li>List 3</li> <li>List 4</li> <li>List 5</li> </ul> </nav> <br/> <button id="menu-btn">Click</button> 

Try this,

var flag=true;

$(function() {
    $('#menu-btn').click(function() {      
        var newMargin = flag==true ? '83px 0px 0px -225px' : '83px 0px 0px 0px';

        $('nav ul').animate({
           margin: newMargin //toggle margin according to flag
        }, 200);

        flag = !flag; //toggle flag
    });
});

Or you can try this -

$('#menu-btn').click(function(){
    if ($('nav ul').css('margin-left') == '225px') {
        $('nav ul').animate({
          margin:'83px 0px 0px 0px'
        }, 200);
    } else {
        $('nav ul').animate({
            margin:'83px 0px 0px 225px'
        }, 200);
    }
});

Issue with your code was that you were trying to get the shorthand property of margin, which as per jQuery's documentation, is not guaranteed to work -

Retrieval of shorthand CSS properties (eg, margin, background, border), although functional with some browsers, is not guaranteed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM