Friday, 1 November 2019

Multi-Function jQuery onClick to Call Script

Having done a lot of research and testing, I've pieced together several snippets to achieve almost 100%, thanks to multiple Stack articles (such as How to Click to show & Click to call?).

Given multiple containers as shown:

<div class="entry-details">
    <p class="phone">+18885551212,,,111</p>
    <p class="address">111 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

<div class="entry-details">
    <p class="phone">+18885551212,,,222</p>
    <p class="address">222 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

<div class="entry-details">
    <p class="phone">+18885551212,,,333</p>
    <p class="address">333 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

<div class="entry-details">
    <p class="phone">+16665551200</p>
    <p class="address">444 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

The goal onClick is to:

  1. Copy p.phone field text to href;
  2. Wrap p.phone field with href tel tag ;
  3. Replace p.phone content with "Click to Call";
  4. On click, show number formatted as # + ext (ex. 888-555-1212 Ext 222) if commas and extension are present, standard tel if not (ex. 888-555-1212).
  5. and finally, dial the # including pauses (commas);
jQuery(document).ready(function($) {
        $('.phone').wrapInner('<a class="phone-link" href=""></a>');
        $('.phone').each(function() {
            var $phoneLink = $(this).find('.phone-link');
            var _linkUrl = $phoneLink.text();
            $(this).find('a.phone-link').attr('href', 'tel:' + _linkUrl).text('Click to Call');
        });

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="entry-details">
    <p class="phone">+18885551212,,,111</p>
    <p class="address">111 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

<div class="entry-details">
    <p class="phone">+18885551212,,,222</p>
    <p class="address">222 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

<div class="entry-details">
    <p class="phone">+18885551212,,,333</p>
    <p class="address">333 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

<div class="entry-details">
    <p class="phone">+16665551200</p>
    <p class="address">444 Any Street, Anytown, NY 10010, USA</p>
    <p class="time">11:00 to 08:00</p>
</div>

I had written another function for the final piece (changing Click to Call on click), but

  1. It didn’t work
  2. It changed all instances of .phone when clicked.


from Multi-Function jQuery onClick to Call Script

No comments:

Post a Comment