Clickable Phone Numbers on Touch Devices

It’s relatively simple to create a link that points to a phone number instead of a URL. However, this only works on devices that have the means to place a call. In a traditional desktop browser, clicking a telephone link leads to an error message or dialog box. While some computers my have a means to place phone calls, it’s not a good user experience for the rest of your site visitors. Let’s look at how we can improve this situation with a little Javascript.

First, we wrap our phone numbers in a span tag with a class of “touch-to-dial” so our script can recognize it as a phone number.

<span class="touch-to-dial">1-800-555-0199</span>

Next we add our Javascript.

jQuery( document ).ready( function( $ ) {
	
	// Adds support for converting phone numbers to links on touch devices.
	if ( 'ontouchstart' in document.documentElement ) {

		// For each element with class "touch-to-dial".
		$( '.touch-to-dial' ).each(function() {
			var ttdPhoneNumber = $( this ).text();

			// Wrap phone number with an anchor and then insert phone number.
			$( this ).wrapInner( '<a href=""></a>' );
			$( this ).find('a').attr( 'href', 'tel:' + ttdPhoneNumber );
		});
	}
});

Please note: this code requires jQuery. Yes, this could be done without jQuery, but the theme I’m currently working on is already using jQuery, so I went ahead and used the jQuery selector system.

First, we wrap our code in jQuery’s ready() function so it doesn’t run until the page content is available to us. Then we use the “ontouchstart” event to determine whether we’re dealing with a touch device. Yes, there are touch devices that don’t have calling capabilities, but it’s a much smaller percentage than for desktop users. Finally, we loop through each element using our “touch-to-dial” class. For each element, we extract the text inside the element into a variable (don’t place anything besides the phone number in this element). Then we add an anchor tag inside the .touch-to-dial element and use the phone number variable along with “tel:” to set the href attribute.

This ensures that desktop browsers see a standard phone number and touch devices are served a link.