Prevent multple click events

PHOTO EMBED

Wed Jan 21 2026 03:22:42 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #dataset #prevent #duplicate #event #listener

/**
 if rerendering occurs or to stop duplicate events

if (button.dataset.recShareTracked) return;
button.dataset.recShareTracked = "true";

*/



// example

 function recShareTracking() {
        const recUserActions = document.querySelector(".rec-user-actions");

        if (!recUserActions) return;

        const shareButtons = recUserActions.querySelectorAll(
            ".rec-user-actions__cta-button",
        );

        if (!shareButtons.length) return;

        console.log({shareButtons})

        shareButtons.forEach((button) => {
            // Prevent duplicate listeners
            if (button.dataset.recShareTracked) return;
            button.dataset.recShareTracked = "true";

            button.addEventListener("click", (e) => {
                const clickedElement = e.target;
                const isButtonClick =
                    clickedElement === button ||
                    clickedElement.closest(".rec-user-actions__cta-button") ===
                        button;

                if (!isButtonClick) return;

                const buttonTextRaw = button.textContent?.trim() || "";
                const buttonText = buttonTextRaw.replace(/\s+/g, " ").trim() || "";

                if (buttonText) {
                    gtmPush({
                        event: "interaction_click",
                        component_name: "button",
                        click_text: buttonText,
                        click_url: null,
                    });
                }
            });
        });
    }
content_copyCOPY