This documentation guides you on how to track cookie collection when a user clicks a specific button. By doing this, you can understand user preferences based on their location, derived from the website's URL.

Objective

When a user clicks the button with the selector #onetrust-accept-btn-handler, the goal is to tag the current session with their cookie preference and their location derived from the URL.

Implementation

Below is the full code with explanations in the comments:

// Wait for the document to be fully loaded before executing the code

document.addEventListener("DOMContentLoaded", function() {



// Function to extract the user's location (e.g., CA) from the URL. Replace the INSERT_URL placeholder

function extractLocationFromURL(url) {

let matches = url.match(/https:\/\/INSERT_URL\/([A-Z]{2})\/en_/);

if (matches && matches[1]) {

return matches[1];

}

return "Unknown";

}



// Function to handle the button click

function handleButtonClick() {

// Extract the user location from the current URL

let userLocation = extractLocationFromURL(window.location.href);

// Tag the session with the user's location using the NoibuJS SDK

NOIBUJS.addCustomAttribute("cookie_preference_selected", userLocation);

}



// Try getting the button immediately

let cookieButton = document.querySelector("#onetrust-accept-btn-handler");



// If the button exists on the page, add a click event listener

if (cookieButton) {

cookieButton.addEventListener("click", handleButtonClick);

} else {

// If the button doesn't exist yet (e.g., it's loaded asynchronously), try again after a delay

setTimeout(function() {

cookieButton = document.querySelector("#onetrust-accept-btn-handler");

if (cookieButton) {

cookieButton.addEventListener("click", handleButtonClick);

}

}, 1000); // The delay can be adjusted based on when you expect the button to be available

}

});

Conclusion

The updated code ensures that even if the #onetrust-accept-btn-handler button isn't immediately available when the code runs, it will attempt to access the button again after a brief delay. This handles scenarios where the button might be loaded asynchronously. Ensure to test the implementation to confirm that it works as desired.