Reputation: 27
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);
}
});
Upvotes: 0
Views: 103
Reputation: 40639
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
});
});
Upvotes: 0
Reputation: 56
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 (e.g., margin, background, border), although functional with some browsers, is not guaranteed.
Upvotes: 0
Reputation: 2921
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
}
Upvotes: 1