How to track and measure phone number views with JavaScript

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.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Thursday, August 22, 2019 in JavaScript

Unlimited Automated Page Speed Monitoring & Tracking. Completely free.
Use SpeedFactor to track your website. It’s simple, reliable, and best of all, it’s free forever.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles


Privacy Policy