As per the following markup code, there is a sticky navigation bar (menu-bar) that reveals an off-canvas menu using CSS transitions when the button is clicked by adding a class (slide-wrapper__open) to the HTML element.
HTML
<div class="menu-bar">
<div class="menu-btn">
<a href="" class="menu-btn__toggle">
<i class="fa fa-bars"></i>
</a>
</div>
</div>
<div class="slide-wrapper">
<nav class="nav-menu">
<ul class="nav-menu__menu">
</ul>
</nav>
</div>
CSS
@import "../modules/mixins";
.menu-bar {
@include mobile {
width: 100%;
height: 50px;
position: fixed;
border-bottom: 1px solid $lightGreyBorder;
background: white;
z-index: 100;
}
@include tablet {
display:none;
}
@include tablet-land {
display:none;
}
@include desktop {
display: none;
}
}
.menu-btn {
@include mobile {
height: inherit;
width: 50px;
text-align: center;
line-height: 50px;
font-size: 1.4rem;
float: right;
}
}
.slide-wrapper {
@include mobile {
width:80%;
position: fixed;
top: 0;
right: 0;
height: 100%;
z-index: 0;
}
@include tablet {
display:none;
}
@include tablet-land {
display:none;
}
@include desktop {
display: none;
}
.nav-menu {
@include mobile {
position: absolute;
background: rgba(0,0,0,0.65);
width: 100%;
right: -100%;
height: 100%;
transition: ease 0.5s all;
}
}
}
.slide-wrapper__open {
.page {
@include mobile {
right: 80%;
transition: ease 0.5s all;
overflow: hidden;
}
}
.slide-wrapper {
right: 0;
top: 0;
height: 100%;
z-index: 0;
.nav-menu {
@include mobile {
right: 0%;
transition: ease 0.5 all;
}
}
}
}
.page {
@include mobile {
width: 100%;
height: 100vh;
position: relative;
right: 0;
transition: ease 0.6s all;
}
}
JS
$(".class").click(function(e){ //stack overflow is giving me code errors but the class name i used was the correct one.
e.preventDefault();
$("html").toggleClass("slide-wrapper__open");
});
However, clicking the link causes the page to scroll all the way to the top of the page and opens the off-canvas menu. Removing the toggle class prevents scrolling but also hides the menu. The issue could be related to CSS transitions or the toggleClass function. Various attempts have been made to solve this issue, such as using return false, #! in the link, or scrolling back to the click position ($(document).scrollTop(SCROLL_POS);). However, these solutions only partially work when the menu is closed; if open (class added to html tag), it still scrolls to the top of the page.
If you have any advice or solutions to this problem, your input would be greatly appreciated.
Thank you
EDIT - Original
EDIT - Working