Search code examples
javascripttel

How to implement telephone links with Javascript


I am working with a WordPress theme and this is the functionality that I am trying to achieve:

<a href="tel:225-1077">225-1077</a>

It sure is easily done with HTML but I am really not good with WordPress and this theme I got has so much files in it that it's hard to find where I should edit however, the theme allows you to add custom JS so I was wondering if the functionality above can be done with JS.

Any help is very much appreciated!


Solution

  • Very simply, it is possible, but that doesn't mean it's a good idea. JS support across mobile phones is not consistent, and not even always enabled, which would mean that these people would never see your link.

    To create the link with JS is simple :

    var cta = document.createElement('a');
    
    cta.href = 'tel:12341234';
    cta.setAttribute('class', 'my cta classes');
    cta.appendChild(document.createTextNode('1234-1234'));
    

    and then you need to put it somewhere on the page. If we have <div>s all over the place with a specific class, we can use that:

    This is our HTML

    <div class="target-cta">This div should receive a link</div>
    <div class=""> this one shouldn't </div>
    <div class="target-cta"> should have one here </div>
    <div class=""> ...though not here</div>
    <div class="target-cta">and finally, one here:</div>
    

    and our JS to insert the links should loop through these elements, creating the links and inserting them as it goes:

    var targets = document.getElementsByClassName('target-cta'),
        target, 
        i, 
        cta; // Call To Action
    
    for (i = 0; i < targets.length; i++) {
    
        target = targets[i];
        cta = document.createElement('a');
    
        cta.href = 'tel:12341234';
        cta.setAttribute('class', 'my cta classes');
        cta.appendChild(document.createTextNode('1234-1234'));
    
        target.appendChild(cta);
    };
    

        var targets = document.getElementsByClassName('target-cta'),
            target, i, cta;
    
        for (i = 0; i < targets.length; i++) {
    
            target = targets[i];
            cta = document.createElement('a');
    
            cta.href = 'tel:12341234';
            cta.setAttribute('class', 'my cta classes');
            cta.appendChild(document.createTextNode('1234-1234'));
    
            target.appendChild(cta);
        };
    <div class="target-cta">This div should receive a link</div>
    <div class=""> this one shouldn't </div>
    <div class="target-cta"> should have one here </div>
    <div class=""> ...though not here</div>
    <div class="target-cta">and finally, one here:</div>