How can I target based on cart state or value?
-
Official comment
In general, you can use the evaluators for the element/object that holds cart items on-page. Usually there is a class being added to the cart element when the user adds a product to the cart - this is one indicator to look for.
Please note: Test this code, these are generic examples only that would most often than not need your modification. this is just to get you started. You can work directly under dev tools -> console, to see the returned value.
Example 1: Number of items in cart (asynchronously) - Recommended
DYO.Q(DYO.waitForElementAsync("<selector>", 1, 10, 100)).then(function(elements) {
return parseInt(elements[0].textContent);
});Example 2: Number of items in cart (synchronously)
//selector is the cart quantity DOM element
parseInt(document.querySelector("<selector>").textContent);
This can then be used as a targeting condition:Example 3: Is cart selector on-page? (indicating that the user added an item to the cart)
DYO.Q(DYO.waitForElementAsync("<selector>",1, 10, 100))
.then(function() {
return "True";
}, function() {
return "False";
});Example 4: Total Cart Value (without the currency symbol)
DYO.Q(DYO.waitForElementAsync("<selector>",1, 10, 100))
.then(function(elements) {
return parseFloat(elements[0].textContent.replace(/[^0-9\.]+/g,""));
}, function() {
return 0;
});Example 5: Total cart value from data layer (when at position 0)
Return the total cart value as taken from the dataLayer attribute, for sites that are integrated with Google Analytics. This assumes the dataLayer is at position 0. You can also add a loop to discover the position of the dataLayer if the position is not 0.
//max retries & interval duration can be changed, make sure you are accessing the right position in dataLayer - in this example its the first index in the array
var MAX_RETRIES = 5;
var FALLBACK_VALUE = 0;
var INETRVAL_IN_MS = 100;
DYO.Q.Promise(function(resolve) {
var retryCounter = 0;
var interval = setInterval(function() {
if (typeof dataLayer === 'object' && typeof dataLayer[0] === 'object') {
clearInterval(interval);
resolve(parseFloat(dataLayer[0].cartValue) || FALLBACK_VALUE);
} else {
retryCounter++;
}
if (retryCounter > MAX_RETRIES) {
resolve(FALLBACK_VALUE);
clearInterval(interval);
}
}, INETRVAL_IN_MS);
});This can then be used as a targeting condition:
Comment actions
Please sign in to leave a comment.
Comments
1 comment