'Javascript onclick event out of phase in Angular
Using Angular framework to build my website's front-end, I'm trying to include a button/icon capable of opening and closing this sidenav:
<nav id="left-sidenav" class="sidenav">
<div class="local_nav">
<a class="link" href="#">About</a>
<a class="link" href="#">Services</a>
<a class="link" href="#">Clients</a>
<a class="link" href="#">Contact</a>
</div>
</nav>
I found a cool hamburger fold-out menu on codepen.io, and I ended up modelling the HTML code this way.
<div id="menuToggle">
<input type="checkbox" onclick="toggleNav()" />
<span></span>
<span></span>
<span></span>
<ul id="menu"></ul>
</div>
With this being the toggleNav() function (added to index.html head):
<script>
//sidenav-width: 150px (this is defined in sidenav.component.scss)
function toggleNav() {
var x = document.getElementById("left-sidenav");
if (x.style.width === "0px") {
//openNav
x.style.width = "150px";
} else {
//closeNav
x.style.width = "0px";
}
}
</script>
So when the page is loaded, it looks like this [please don't mind the image, it's my first time using Angular and I'm trying to get better :) ]: Reloaded page
Now, for some reason, when trying to use this burger menu the first click doesn't trigger the onclick event, and the icon ends up transforming (as it should do) in a cross (see the codepen.io CSS). Page after the first click
On the second click though, the event seems to start working and the sidenav finally shows up, with the cross reverting into the burger icon. If I keep clicking on the burger, it just works as it should, with the icon being out of phase. Page after the second click; Page after the third click
This makes no sense to me, and I initially wanted to get the cross when the sidenav is shown, not when it's hidden. Does anyone know how to actually fix this?
Solution 1:[1]
You can change the implementation of the function toggleNav() for this:
In your .ts file add this.
toggle: boolean = false;
toggleNav() {
this.toggle = !this.toggle;
window.scrollTo(0, 0);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jose Vicente |
