Reputation: 21
I'm trying to have the text content of the closest html tag (with id) added to my facebook pixel standard event parameter. It should work with any html tag, I'd like it to be flexible whether if the text is within a div, span, p, or else.
Below is the jQuery I added to my GTM tag. Note that the {{Click Element}} is a native GTM variable. Also note that the GTM trigger I'm using to fire the GTM tag (so the below jQuery code) is set so the script is launched when clicking on the "buy" class (see HTML code).
<script>
// look for the content_name
var presentElement = {{Click Element}};
var product_name_element = presentElement;
var cond = true;
while(cond){
if(product_name_element.id=="product_name"){
cond = false;
}else{
product_name_element = product_name_element.previousElementSibling;
}
}
var product_name = product_name_element.textContent;
fbq('track', 'AddToCart', {
content_name: product_name
});
</script>
And the HTML:
<p id="product_name">Product 1</p>
<p><a href="#" class="buy">Order</a></p>
<p id="product_name">Product 2</p>
<p><a href="#" class="buy">Order</a></p>
Any help would be really pleased!
Many thanks.
Upvotes: 0
Views: 192
Reputation: 8736
In your case you need to create trigger:
Then create tag:
HTML
<script>
// look for the content_name
var presentElement = {{Click Element}};
var product_name_element = presentElement.parentElement;
var cond = true;
while(cond && product_name_element!= null){
if(product_name_element.id=="product_name"){
cond = false;
}else{
product_name_element = product_name_element.previousElementSibling;
}
}
if (product_name_element != null) {
var product_name = product_name_element.textContent;
fbq('track', 'AddToCart', {
content_name: product_name
});
}
</script>
Trigger - trigger defined above
Upvotes: 0