<target-toggler> Web Component

Posted on December 22, 2023
Takes about 2 minutes to read

There are very rare occasions that I want <details> element disclosure widget-style funtionality but would like to have the <summary> element detached or live outside of it's related <details> container. This commonly stems from designs that may, for example, expect a toggle button to appear inline with other controls or content. Here's my attempt at a Web Component to handle that pattern.

The gist of this component is to enhance an HTML <button> with the ability to toggle an element's visibility anywhere on a page. Simply wrap a button element with this component and supply a target-id attribute that matches the id of any page element.

<script type="module" src="target-toggler.js"></script>

<target-toggler target-id="more-info">
  <button>Show more info</button>

<section>A special announcement</section>

<section id="more-info">
  <!-- some additional information -->

In the above example, a hidden attribute will be added to the targeted more-info element. Now the button toggle can control the visibility of that piece of content. Want that content to be visible by default? Add a target-visible attribute.

<target-toggler target-id="more-info" target-visible>
  <button>Show more info</button>

Be sure to check out the demo page for examples of this component in action.


Want to weigh in? Add a new issue to the repo and share your ideas! I highly value any community feedback on how to improve this implementation.

Helpful resources

Back to all blog posts

Webmentions for this post Learn about webmentions

4 replies
  • Ryan Mulligan
    I know this concept isn't anything new. I'm sure others before me have developed similar patterns. If you know of any, please share them. I'd love to include them on this post ????
  • Nicöd·e
    @hexagoncircle Thanx for sharing :)I didn't know about AbortController, and I've read the doc:https://developer.mozilla.org/en-US/docs/Web/API/AbortControllerI understand their example, with a button to abort loading the video, but in your case, what can abort? Could you explain? AbortController - Web APIs | MDN
  • Ryan Mulligan
    @kizu @keithamus Oh this is great! Thanks for sharing, Roma
  • Mario
    @hexagoncircle I actually had the same idea yesterday. ????Could be cool to make it able to toggle classes and other attribute( value)s as well.