Reputation: 21
I build a nav menu with jquery, when I clicked on menu icon it will open but when I clicked again on menu icon it will not close
this is html code:
<aside class="aside_menu">
<span class="arrow"></span>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
</aside>
this is jquery code:
$(document).ready(function () {
$(".aside_menu .arrow").click(function () {
var aside_menu = $(this).parent();
if (aside_menu.offset().right === 0)
aside_menu.animate({right: "-200px"})
else
aside_menu.animate({right: "0px"})
})
})
the menu hide in the right side of page and only menu icon show up
sorry for bad language
Upvotes: 1
Views: 774
Reputation: 993
Simple things after the biggest resistance line, instead of jQuery, it's better to use JS for such simple things. In addition, animations in JS are clumsy, especially on weaker com-puter and smartphones, which destroys user experience. It's much easier to do it with simple JS and CSS. Probably my code will not help you, but I hope to guide you on the right path. Ps. Try not to use: "_" (underline) in classes and attributes and id's, because it is in terms of SEO, it is a shot in the knee, a better alternative is: "-" (dash).
var menu = document.querySelector("#menu");
var button = document.querySelector("#button");
function toggleMenu(){
if(!menu.classList.contains("fade")){
menu.classList.add("fade");
}else{
menu.classList.remove("fade");
}
}
button.addEventListener("click", toggleMenu);
body{
margin: 0;
display: flex;
}
#menu{
background: pink;
width: 70px;
height: 100%;
text-align: center;
transition: 0.34s;
}
#button{
height: 30px;
transition: 0.34s;
}
.fade{
width: 0 !important;
}
.fade *{
display: none;
}
<aside id="menu" class="fade">
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
<div><a href="#">test</a></div>
</aside>
<button id="button">
Button
</button>
Upvotes: 1
Reputation: 355
.offset()
returns an object containing the properties top
and left
, so your code will never work because aside_menu.offset().right
is always undefined. See http://api.jquery.com/offset/
You have to use aside_menu.offset().left
and then find the proper values to use in the if
condition according to your page layout.
Upvotes: 0