Click Mirror

By Casey Muns

The Goal:

Mirror mouse clicks from one element to another

Use case:

Create a tabs element with a hidden tab-menu and use a custom link menu to switch between tabs.

Tab One

Tab Two

Tab Three

Tab One B

Tab Two B

Tab Three B

<script>
document.addEventListener('click', function(event) {
    // Find the closest ancestor of the clicked element (including itself)
    // that has the 'click-mirror-source' attribute.
    const sourceElement = event.target.closest('[click-mirror-source]');

    // Proceed only if such an element was found.
    if (sourceElement) {
        // Extract the 'click-mirror-source' value.
        const sourceValue = sourceElement.getAttribute('click-mirror-source');

        // Use the value to find all corresponding 'click-mirror-target' elements.
        document.querySelectorAll(`[click-mirror-target="${sourceValue}"]`).forEach(targetElement => {
            // Simulate a click on each target element.
            const clickEvent = new MouseEvent('click', {
                bubbles: true,
                cancelable: true
            });
            targetElement.dispatchEvent(clickEvent);
        });
    }
});
</script>

Implement in Webflow:

1. Install the SCRIPT:

  • Put the script in the custom code section in page settings or in an on page HTML embed.

2. Set up click SOURCES:

  • On the element that you want to trigger the click event, add the attribute click-mirror-source="source1"

3. Set up click TARGETS:

  • On the element that you want to receive the click event, add the attribute click-mirror-target="source1"

4. That's it.

  • You can replace "source1" with any identifier you want.
  • You can have multiple sources/targets on the page. Just make sure the source and target elements have matched identifiers.
  • If there are multiple targets matching one source it will click them all.