E-commerce data tracking with JavaScript

To learn your visitors’ behavior, take action and sell more, you need to track user data on your website.

To launch triggered e-commerce campaigns, you'll need to track these events: viewing items, adding them to the shopping cart, making an order, etc.

Our instruction below will help you track the following data:

Lead properties:

  • Viewed items
  • Cart
  • Cart amount
  • The number of orders
  • Last order amount
  • Total amount of all orders

Lead events:

  • Viewed the item
  • Item added to cart
  • Viewed the cart
  • Started to make an order
  • Made an order

Lead properties are displayed on the left part of a lead card. Lead events are displayed in the middle part of the lead card, in chronological order. You can read more about events and properties here.

Use our code template containing the code to record all of the properties and events necessary for e-commerce data tracking and triggered campaigns. The code must be added into the code input field in the "Settings – "Visitors data tracking" – "Configure the JavaScript code" section.

Please note: If you already have a code inserted in the "Configure the JavaScript code" section, the next one should be added in the new line.


Events and properties for viewing items and adding them to the shopping cart

Add a code template to "Settings – "Visitors data tracking" – "Configure the JavaScript code" section:

if (location.href.indexOf('/POINT1/') > -1) {
    var name = document.querySelector('POINT2').textContent;
    var url = location.href;
    var amount = parseInt(document.querySelector('POINT3').textContent.replace(/\D/g, ''));
    var img = /* location.origin + */ document.querySelector('POINT4 img').getAttribute('src');

    dashly.track('$product_viewed', {
        '$name': name,
        '$url': url,
        '$amount': amount,
        '$img': img
    });

    dashly.identify([{ op: "union", key: "$viewed_products", value: name }]);
    document.querySelector('POINT6').onclick = function() {
        dashly.track('$cart_added', {
            '$name': name,
            '$url': url,
            '$amount': amount,
            '$img': img
        });

        dashly.identify([
            { op: "union", key: "$cart_items", value: name },
            { op: "add", key: "$cart_amount", value: amount }
        ]);
    };
};

1. Enter the value from the link which is repeated on every item page. Replace POINT1 in the code with this value.

Example:

Let’s say we have this link to an item page:  http://woocommerce.dashly.io/catalog/product/shirts/11084green_shirt . We’ll take  /product/  as the value in this link:

if (location.href.indexOf('/product/') > -1) {

1.1. If there is no such value in item links, use an element selector only present on item pages. In that case the first line of code should be replaced with this:

if (document.querySelectorAll('POINT 1.1').length > 0) {

Enter this unique value in place of POINT1.1. For example, let’s say your website has the class=”product” attribute that can only be found on item pages. In that case, we can add .product into the code:

if (document.querySelectorAll('.product').length > 0) {

2. Define element selector containing the item title:

In our example the selector is .product-title . Replace POINT2 with .product-title:

var name = document.querySelector(' .product-title ').textContent;

If you prefer element id as value, use the “#” symbol instead of “.” in the template (#product-title  instead of .product-title )

3. Item price. Define price element selector. Use a value that is unique on this page (we’ll use  .js-prices-current  for our example):

var amount = parseInt(document.querySelector(' .js-prices-current ').textContent.replace(/\D/g,''));

4. Item image. Define the unique CSS-selector of an element with the image. There should be an attribute containing a link to the image storage (you will see a picture if you click on this link in your browser).

The value in our example is .gallery-large_image:

var img = POINT5 document.querySelector('.gallery-large_image').getAttribute('src');

5. Let’s also check whether the link to the picture contains a domain. If the link looks like “https://domain…”, then just leave the “/* location.origin + */” code as it is in the template. If there is no domain in the link, remove the “/*” and “*/” on both sides of “/* location.origin + */”.

6. Define the selector of the "Add to cart" button. For our example, let it be button.product-buy. When a user clicks this button, an event and a property should be recorded:

document.querySelector('button.product-buy ').onclick = function() {

Let's check:

if (location.href.indexOf('/product/') > -1) { 
    var name = document.querySelector('.product-title').textContent; 
    var url = location.href; 
    var amount = parseInt(document.querySelector('.js-prices-current').textContent.replace(/\D/g, '')); 
    var img = /* location.origin + */ document.querySelector('.gallery-large_image img').getAttribute('src');
        
    dashly.track('$product_viewed', { 
        '$name': name, 
        '$url': url, 
        '$amount': amount, 
        '$img': img 
    });
        
    dashly.identify([{ op: "union", key: "$viewed_products", value: name }]);
        
    document.querySelector('button.product-buy').onclick = function() { 
        dashly.track('$cart_added', { 
            '$name': name, 
            '$url': url, 
            '$amount': amount, 
            '$img': img 
        });
        
        dashly.identify([ 
            { op: "union", key: "$cart_items", value: name }, 
            { op: "add", key: "$cart_amount", value: amount } 
        ]); 
    }; 
};

If item pages on your website have a CSS-selector exclusive to item pages, here is what you should have in "Configure the JavaScript code":

if (document.querySelectorAll('.product').length > 0) { 
    var name = document.querySelector('.product-title').textContent; 
    var url = location.href; 
    var amount = parseInt(document.querySelector('.js-prices-current').textContent.replace(/\D/g, '')); 
    var img = /* location.origin + */ document.querySelector('.gallery-large_image img').getAttribute('src');
    
    dashly.track('$product_viewed', { 
        '$name': name, 
        '$url': url, 
        '$amount': amount, 
        '$img': img 
    });
    
    dashly.identify([{ op: "union", key: "$viewed_products", value: name }]);
    
    document.querySelector('button.product-buy').onclick = function() { 
        dashly.track('$cart_added', { 
            '$name': name, 
            '$url': url, 
            '$amount': amount, 
            '$img': img 
        });
    
        dashly.identify([ 
            { op: "union", key: "$cart_items", value: name }, 
            { op: "add", key: "$cart_amount", value: amount } 
        ]); 
    }; 
};

Events and properties on the shopping cart page

Use this code template with "Configure the JavaScript code" section:

if (window.location.href == 'POINT1') {

    function get_items() {
        dashly.identify([{ op: "delete", key: "$cart_items", value: 0 }]);
        var items = document.querySelectorAll('POINT2');
        var m = [];
    if (items.length > 0) {
            for (var i = 0; i < items.length; i++) {
                m.push({ op: "union", key: "$cart_items", value: items[i].textContent.replace(/\s\s/g, '').replace(/\t/g, '') })
            };
            dashly.identify(m);
        } else {
            dashly.identify([{ op: "delete", key: "$cart_items", value: 0 }])
        };

        dashly.identify([{ op: "update_or_create", key: "$cart_amount", value: parseInt(document.querySelector('POINT3').textContent.replace(/\s/g, '')) }]);
        localStorage['lastAmount'] = parseInt(document.querySelector('POINT3').textContent.replace(/\D/g, ''));
    };
    get_items();

    dashly.track('$cart_viewed');
    document.querySelector('POINT4').addEventListener('click', function() {
        setTimeout(function() {
            get_items();
        }, 1000);
    });
    document.querySelector('POINT5').addEventListener('click', function() {
        dashly.track('$order_started');
    });
};

1. Enter a full link to the shopping cart page in place of POINT1. For example:

if (window.location.href == "http://woocommerce.dashly.io/personal/cart/") {

2. On the shopping cart page, find a selector of elements containing the names of the items added to cart and replace POINT2 with it. When Dashly tracks data on the shopping cart page, the number of elements found with this selector should match the amount of items added to the shopping car. Example:

var items = document.querySelectorAll('.bx_ordercart_itemtitle a');

3. Find an element containing the total amount in the shopping cart and enter the CSS-selector of this element in place of POINT3. You should duplicate this value in the template. Example:

dashly.identify([{ op: "update_or_create", key: "$cart_amount", value: parseInt(document.querySelector('#allSum_FORMATED').textContent.replace(/\s/g, '')) }]);
localStorage['lastAmount'] = parseInt(document.querySelector('#allSum_FORMATED').textContent.replace(/\D/g, ''));

4. Find an element with the button or link for removing a cart item and enter the CSS-selector of this element in place of POINT4. Example:

document.querySelector('.control :first-child').addEventListener('click', function() {

5. Add the “Start checkout” button selector instead of POINT5. Example:

document.querySelector('.checkout').addEventListener('click', function() {

Let's check:

if (window.location.href == 'http://woocommerce.dashly.io/personal/cart/') {

    function get_items() {
        dashly.identify([{ op: "delete", key: "$cart_items", value: 0 }]);
        var items = document.querySelectorAll('.bx_ordercart_itemtitle a');
        var m = [];
        if (items.length > 0) {
            for (var i = 0; i<</span > items.length; i++) {
                m.push({ op: "union", key: "$cart_items", value: items[i].textContent.replace(/\s\s/g, '').replace(/\t/g, '') })
            };
            dashly.identify(m);
        } else {
            dashly.identify([{ op: "delete", key: "$cart_items", value: 0 }])
        };

        dashly.identify([{ op: "update_or_create", key: "$cart_amount", value: parseInt(document.querySelector('#allSum_FORMATED').textContent.replace(/\s/g, '')) }]);
        localStorage['lastAmount'] = parseInt(document.querySelector('#allSum_FORMATED').textContent.replace(/\D/g, ''));
    };
    get_items();

    dashly.track('$cart_viewed');
    document.querySelector('.control :first-child').addEventListener('click', function () {
        setTimeout(function () {
            get_items();
        }, 1000);
    });
    document.querySelector('.checkout').addEventListener('click', function () {
        dashly.track('$order_started');
    });
};

Events and properties of a completed order

Add a code template to "Configure the JavaScript code" section:

if (location.href.indexOf('POINT1') > -1) {
    dashly.track('$order_completed', {
        '$order_amount': localStorage['lastAmount'],
        '$order_id': document.querySelector('POINT2').textContent.replace(/\D/g, '')
    });
    dashly.identify([{ op: "delete", key: "$cart_items", value: 0 }]);
    dashly.identify([{ op: "delete", key: "$viewed_products", value: 0 }]);
    dashly.identify([{ op: "delete", key: "$cart_amount", value: 0 }]);
    dashly.identify([{ op: "add", key: "$revenue", value: localStorage['lastAmount'] }]);
    dashly.identify([{ op: "add", key: "$orders_count", value: 1 }]);
    dashly.identify([{ op: "update_or_create", key: "$last_payment", value: localStorage['lastAmount'] }]);
    localStorage.removeItem('lastAmount');
};

1. Replace POINT1 with a part of the URL of the order confirmation page. Example:

if (location.href.indexOf('?ORDER_ID') > -1) {

2. Find a selector of an element containing a unique order number and insert it in POINT2. Example:

document.querySelector('.sale_order_full_table b').textContent.replace(/\D/g, '')

Let's check:

if (location.href.indexOf('?ORDER_ID') > -1) {
    dashly.track('$order_completed', {
        '$order_amount': localStorage['lastAmount'],
        '$order_id': document.querySelector('?ORDER_ID').textContent.replace(/\D/g, '')
    });
    dashly.identify([{ op: "delete", key: "$cart_items", value: 0 }]);
    dashly.identify([{ op: "delete", key: "$viewed_products", value: 0 }]);
    dashly.identify([{ op: "delete", key: "$cart_amount", value: 0 }]);
    dashly.identify([{ op: "add", key: "$revenue", value: localStorage['lastAmount'] }]);
    dashly.identify([{ op: "add", key: "$orders_count", value: 1 }]);
    dashly.identify([{ op: "update_or_create", key: "$last_payment", value: localStorage['lastAmount'] }]);
    localStorage.removeItem('lastAmount');
Powered by