How to track and measure phone number views with JavaScript

Ciprian on Thursday, August 22, 2019 in JavaScript DOM

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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

2 comments on “How to track and measure phone number views with JavaScript

  1. Dear Ciprian,
    This code is fantastic! It works very well – if there is only one phone number to reveal on the page.
    At the moment I’m working on a landing page for a “not-perfect” site to run an ad campaign. I’d like to measure click events so that is why I’d like to hide-reveal the phone number.
    The problem is, that I’d like to repeat the “button” on the page and this way the code doesn’t work properly. I thought I should modify the class in the link as well as in the script, (reveal-number, reveal-numb, reveal-number1) but it doesn’t work.
    Could you please help? Unfortunately I’m a no-coder… but I’m trying my best :)
    Thank you for your help in advance.
    Kind regards,
    Rita

Leave a Reply

Your email address will not be published. Required fields are marked *