I am coding a simple website with a JS side navbar. When I resize the window to develop at different widths I noticed that the page would jump to the top. I then noticed that when I click the hamburger icon the page also jumps to the top.
I've looked into it and it appears to be the onClick that is the issue. I have tried to use return false but the issue is still the same.
I have used the code/tutorial provided on w3 schools. Thanks for any help
Here is my code
HTML:
<nav id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav();return false;">×</a>
<img class="sidenavbar-logo-img" src='<?php echo get_template_directory_uri(); ?>/img/logo-NO.png'>
<?php wp_nav_menu( array( 'theme_location' => 'sidenav-menu' ) ); ?>
<div class='sidebar-nav-info'>
<p>Lower Trinity St,
Birmingham,
B9 4AG</p>
<p>Facebook Instagram</p>
</div>
</nav>
<!-- Use any element to open the sidenav -->
<span class="hamburger" onclick="openNav(); return false;">
<i class="fas fa-bars"></i>
</span>
CSS
/* The navigation menu links */
.sidenav ul {
list-style-type: none;
margin-left: 0;
}
.sidenav ul li {
margin: 0;
}
.sidenav a {
padding: 8px 8px 8px 0px;
text-decoration: none;
font-weight: 700;
font-size: 18px;
color: #f1f1f1;
display: block;
transition: 0.3s;
}
/* When you mouse over the navigation links, change their color */
.sidenav a:hover {
color: #818181;
text-decoration: none;
}
/* Position and style the close button (top right corner) */
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
transition: margin-left .5s;
padding: 20px;
}
/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
.sidebar-nav-info {
padding: 30px;
position: absolute;
bottom: 0;
left: 0;
width: 200px;
color: #E2E2E2;
font-size: 12px;
}
/** HAMBURGER ICON **/
span.hamburger {
position: sticky;
top: 30px;
left: 30px;
font-size: 30px;
font-weight: 800;
cursor: e-resize;
}
JS
<script>
/* Set the width of the side navigation to 250px and the left margin of the page content to 250px */
function openNav() {
document.getElementById("mySidenav").style.width = "300px";
document.getElementById("main").style.marginLeft = "300px";
}
/* Set the width of the side navigation to 0 and the left margin of the page content to 0 */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
</script>