Last active
October 8, 2022 07:16
-
-
Save chavesm/c765a7c93df7a9f5bbd3348bd3fe548f to your computer and use it in GitHub Desktop.
Send an exit-intent event to GA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Exit - intent event demo */ | |
(function () { | |
if (!document.URL.includes("simple-form")) return; | |
const beforeUnloadListener = (event) => { | |
event.preventDefault(); | |
// GA code goes here. | |
// Below is an example using gtag.js API. | |
__gtagTracker('event', 'page-exit', { | |
'event_category': 'input-field', | |
'event_action': 'exit-intent', | |
'event_label': 'input-name', | |
'value': 1 | |
}); | |
return event.returnValue = "Are you sure you want to exit?"; | |
}; | |
const nameInput = document.querySelector("#avia_1_1"); | |
nameInput.addEventListener("input", (event) => { | |
if (event.target.value !== "") { | |
// If something's in the input field listen for exit intent. | |
addEventListener("beforeunload", beforeUnloadListener, { capture: true }); | |
} else { | |
removeEventListener("beforeunload", beforeUnloadListener, { capture: true }); | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment