Button unable to show the sidebar menu

At first load of the page. The button for showing the sidebar menu works.
After visiting other pages the button is not toggling the sidebar anymore.

How can i fix this?

My guess is that the event-handlers for the button are being managed outside of a Stimulus controller; as such, they aren’t being re-bound when the <body> tag is replaced on subsequent visits. How are you attaching event-handlers?

I’m using a third party plugin to handle the toggling of the sidebar.

I’m relatively new to Stimulus; but, I believe the best practice in this case (short of rewriting everything) is to use a light-weight Stimulus controller to handle the initialization of the 3rd-party widget. Just some pseudo-code, but something like:

import { Application } from "@hotwired/stimulus";
import { Controller } from "@hotwired/stimulus";

class MenuController  extends Controller {
	connect() {
		some3rdPartyWidget.init( this.element );
	}

	disconnect() {
		some3rdPartyWidget.destroy( this.element );	
	}
}

window.Stimulus = Application.start();
Stimulus.register( "my-menu", MenuController );

The goal here of this Stimulus controller is really only to make sure that the 3rd-party library is setup/torn-down when the DOM changes. The connect() callback is invoked when the controller is attached to the DOM (such as on page load); and the disconnect() callback is invoked when the controller is detached from the DOM.

Then in your HTML, you’d have something like:

<div data-controller="my-menu">
    <!-- Your menu markup. -->
</div>

Does that make sense? Then, as Turbo Drive moves around in the app, and swaps out the <body> content, your Stimulus controller will make sure that your 3rd-party library is attached/removed as needed.

I should also clarify that the root issue is the fact that once Turbo Drive kicks in, there are no longer any full page reloads as you move around in the app, which is likely what you needed for your 3rd-party library to get initialized. The Stimulus controller life-cycle methods stand-in for your “page loads”, if you will.

It works now.

Thank you @BenNadel for your detailed explanation! :slight_smile:

1 Like

Awesome :clap: my pleasure.