Skip to content

Instantly share code, notes, and snippets.

@mrjonesbot
Created April 25, 2022 22:03
Show Gist options
  • Save mrjonesbot/bf8304debf4721afb87c4df409dbc629 to your computer and use it in GitHub Desktop.
Save mrjonesbot/bf8304debf4721afb87c4df409dbc629 to your computer and use it in GitHub Desktop.
Light Stimulus controller that manages accordion side navigation behavior
import ApplicationController from './application_controller'
export default class extends ApplicationController {
static targets = ["selectable"]
static values = {
selectedClass: String
}
select(event) {
const previousElement = this.selectableTargets.find(target => target.classList.contains(this.selectedClassValue))
// sometimes clicking an element will focus, but not mark it selected
// e.g. clicking an arrow to reveal a sub menu
if (previousElement != undefined) {
previousElement.classList.toggle(this.selectedClassValue)
}
event.target.classList.toggle(this.selectedClassValue)
}
}
@mrjonesbot
Copy link
Author

mrjonesbot commented Apr 25, 2022

With this controller, you can wrap and target navigation links that you want to mark as "selected" or "active".

<span data-controller='navigation' data-navigation-selected-class-value='bg-gray-200' data-turbo-permanent>
  <%= link_to url, class: "hover: text-gray-900 hover:bg-gray-100 bg-gray-200", data: { navigation_target: "selectable", action: "navigation#select" } %>
  <%= link_to url, class: "hover: text-gray-900 hover:bg-gray-100" %>
</span>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment