Skip to content
On this page

Changing state when clicking outside of an element

This feature should be enabled in the controller element with
data-action="click@window->toggler#clickOutside".

It will set variables when clicking outside this element, with
data-toggler-click-outside="...".

Click-outside can be ignored in other element if it is set in it
data-toggler-click-outside-ignore="...".

Input

html
<div data-controller="toggler" data-action="click@window->toggler#clickOutside" class="example">
    <!-- togglers -->
    <button id="btn_toggle_9" data-toggler-states="+9" data-toggler-click-outside="-9" class="flex">
        <svg data-toggler-target="toggleable" data-toggler-listen="9" data-toggler-classes="hidden" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 mr-2"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" /></svg>
        <svg data-toggler-target="toggleable" data-toggler-listen="9"                               xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 mr-2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
        Show 9 & hide if click outside
    </button>
    <button id="btn_toggle_10" data-toggler-states="+10" data-toggler-click-outside="-10" class="flex">
        <svg data-toggler-target="toggleable" data-toggler-listen="10" data-toggler-classes="hidden" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 mr-2"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" /></svg>
        <svg data-toggler-target="toggleable" data-toggler-listen="10"                               xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 mr-2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
        Show 10 & hide if click outside except in div tenth (ignoring)
    </button>
    <!-- elements to toggle -->
    <div id="div_9" class="bg" data-toggler-target="toggleable" data-toggler-listen="9">
        Nineth (9) - if you click here inside this div will be hidden
    </div>
    <div id="div_10" class="bg" data-toggler-target="toggleable" data-toggler-listen="10" data-toggler-click-outside-ignore="-10">
        Tenth (10) with ignore  - if you click here inside this div will NOT be hidden
    </div>
</div>

Output

Nineth (9) - if you click here inside this div will be hidden
Tenth (10) with ignore - if you click here inside this div will NOT be hidden

INFO

click-outside-ignore is very useful for elements as dropdowns, where you want them to be hidden only if you click outside the dropdown itself