Skip to content

Instantly share code, notes, and snippets.

@mrjonesbot
Last active July 3, 2022 14:25
Show Gist options
  • Save mrjonesbot/4b1f2d345afbfb99e5256a2c46ec64dd to your computer and use it in GitHub Desktop.
Save mrjonesbot/4b1f2d345afbfb99e5256a2c46ec64dd to your computer and use it in GitHub Desktop.
Basic toggle controller to show/hide elements
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "toggleable" ]
connect() {
this.toggleClass = this.data.get("class") || "hidden"
}
toggle(event) {
event.preventDefault()
this.toggleableTargets.forEach( target => {
target.classList.toggle(this.toggleClass)
})
}
}
@mrjonesbot
Copy link
Author

mrjonesbot commented Apr 25, 2022

When implementing sidebar navigation with collapsable subsections, you can use the toggle controller to show/hide the subsections using whatever icon you'd like (in this case, an arrow).

<div class='my-2' data-controller='toggle'>
   <!-- section icon -->
   Name of section
  
  <!-- arrow right and arrow down -->
  <svg class="text-gray-300 ml-3 flex-shrink-0 h-5 w-5 transform group-hover:text-gray-400 transition-colors ease-in-out duration-150" viewBox="0 0 20 20" aria-hidden="true" data     -action='toggle#toggle' data-toggle-target='toggleable'>
   <path d="M6 6L14 10L6 14V6Z" fill="currentColor" />
  </svg>
  <svg class="hidden ml-3 flex-shrink-0 h-5 w-5 transform group-hover:text-gray-400 transition-colors ease-in-out duration-150 text-gray-400 rotate-90" viewBox="0 0 20 20" aria-h     idden="true" data-toggle-target='toggleable'>
  <path d="M6 6L14 10L6 14V6Z" fill="currentColor"></path>
  </svg>

  <!-- links subsection -->
  <div class="space-y-1 hidden" id="sub-menu-1" data-toggle-target='toggleable'>
    <%= link_to url, class: "hover:text-gray-900 hover:bg-gray-50" %>
  </div>
</div>

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