Skip to content

Toggle

The h-toggle webcomponent provides a simple and reusable way to show or hide content within your application. It acts as a toggleable container that can encapsulate any content, allowing for dynamic visibility based on user interactions or programmatic control. This component is particularly useful for creating expandable sections, modals, or any UI elements that require show/hide functionality.

Note: h- stands for headless. This is naming convention used for every webcomponent as they must have a two-part name.

Attributes

Attribute name Type Default Description
opened boolean false Determines if the toggle content is visible (true) or hidden (false).

Toggle API

The h-toggle webcomponent provides the following public methods to control its state programmatically:

toggle(): void

Toggles the visibility of the content. If the content is currently visible (opened is true), calling this method will hide it, and vice versa.

const toggle = document.querySelector('h-toggle#my-toggle');
toggle.toggle();

DOM Events

The h-toggle listens to the following DOM Events:

Example

In this example we render a basic toggle element with a button that fires the toggle method.

HTML
<h-toggle id="my-toggle">
    <template>
        <div class="toggle-content">
            <p>This content is toggleable.</p>
        </div>
    </template>
</h-toggle>

<button id="toggle-btn">Toggle Content</button>
JS
useStorefront(async (storefront) => {
    function handleToggle() {
        const $toggle = document.querySelector('h-toggle#my-toggle');
        $toggle.toggle();
    }

    const $toggleBtn = document.querySelector('button#toggle-btn');

    $toggleBtn.addEventListener('click', handleToggle);
});

Example

In this example we use the h-toggle-btn to integrate with the h-toggle webcomponent.

HTML
<h-toggle opened>
    <h-toggle-btn action="expand">Toggle Content</h-toggle-btn>
    <h-toggle-btn action="collapse" hidden>Toggle Content</h-toggle-btn>
    <template>
        <div class="toggle-content">
            <p>This is the toggleable content.</p>
        </div>
    </template>
</h-toggle>

Webcomponents reference