FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

How to track and measure phone number views with JavaScript

on in JavaScript DOM
Last modified on

Use this tutorial to create phone number links and track/measure views.

As phone numbers are clickable (and work) only on mobile devices, there’s no way to track how many users copy them or write them down. Well, unless they’re hidden and require user access. Here’s how to do it.

Create a clickable phone number link:

<a href="tel:09483473843" class="reveal-number" data-number="094 834 73 843">094 834 73 843</a>

Add a function to hide the last 4 characters and show them on click. Additionally, there’s a timeout event to explain the user what to do next.

function reveal_number_init() {
    let phoneNumbers = document.getElementsByClassName('reveal-number');

    let replaceLastNChars = function(str, replace, num) {
        return str.slice(0, -num) + Array(num + 1).join(replace);
    };

    for (i = 0; i < phoneNumbers.length; i++) {
        var element = phoneNumbers[i];

        element.href = 'javascript:void(0);';
        element.innerText = replaceLastNChars(element.innerText, '*', 4);

        element.addEventListener('click', function (event) {
            element.innerText = element.dataset.number;

            setTimeout(function () {
                element.href = 'tel:' + element.dataset.number;
                element.innerHTML += '<br><small class="phone-reveal-help">Click again to call.</small>';
            }, 1000);
        });
    }
}

Initialise the function:

document.addEventListener('DOMContentLoaded', function () {
    if (document.querySelector('.reveal-number')) {
        reveal_number_init();
    }
});

Next, you can use an AJAX call to store the phone number clicks, depending on your content management system or your database structure.

Related posts