Mcdostone Mcdostone - 1 month ago 10
CSS Question

Clicks on links anchor disable my JS listeners

I've created a responsive menu with the famous hamburger.
This menu contains only links that point to an anchor in the same page.

When you click on this hamburger icon, it show the menu. But when I click on one link, The location changes but the menu is hidden and it is impossible de show it again.

let toggleMenu = function(e) {
console.log(e)
document.querySelector('.nav').classList.toggle('hidden')
}

window.onload = function(e) {
document.querySelector('.nav-container-hamburger').addEventListener(
'click',toggleMenu)


}

<body>
<navbar>
<a id='navbar-logo'>
<img src="/images/logo_studio.png" alt="Logo studio" />
</a>
<div class='nav-container-hamburger'>
<div class='nav-hamburger'></div>
</div>
<div class='nav hidden'>
<div class='nav-left'>
<a href="/#studio">Studio</a>
<a href="#works">Réalisations</a>
<a href="#about">À propos</a>
</div>
<div class='nav-right'>
<a id="sign_in" href="/auth/google_oauth2">Se connecter</a>
</div>
</div>
</navbar>




.hidden {
display: none;
opacity: 0;
height: 0;
}


It seems all listeners have been deleted because when I click on the hamburger, nothing is displayed in the console ...

It's very strange because I can show and hide the menu infinitely if I don't click on a anchor link.

I have checked with the console, the listener is still there but I can't trigger it by clicking on the hamburger!

Answer

I finally found the solution: Rails uses turbolinks in order to make faster navigation. However, in this case, turbolinks is the cause of the problem:

So you have just to disable it for links:

= link_to "À propos", "/#about", data: { turbolinks: false }

Comments