While working with seo optimization, many times we need to include phone dialer on all valid phone on website for its better work.
Here I have created an script which can automatically add dialer to href with refrence of same number that phone is written in anchor tag. With help of this we can reduce multiple hour of reentering or adding phone inside anchor dialer of phones.
For this we have created a regex which will identifies numbers on entire webpage.
For this we are focusing only on text which is matching phone number digits, To do this we are using javascript nodeType property of dom element, which will gives nodeType as(node type of element text in dom is 3) . We are also using regex to find matched string that has node type 3 and has anchor tag, then i have created a dialer element anchor tag and then replaced with original node text. You can use below script to filter some phone numbers in whole pages and create dialer for same or you can also do for all numbers too.
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g; ---Finding Phone Numbers
var text = $("body:first").html();
var textNodes = $("body:first").find('*').contents().filter(function () {
if (this.nodeType == 3 && regex.test(this.nodeValue) && this.parentElement.tagName !== "A") {
var anchor = document.createElement('a');
//********Tel No. Trimming************
var telno = this.nodeValue.match(regex)[0];
var telno1 = telno.replace(/\s/g, ''); -- Replacing space with null
var telnot = telno1.replace(/[:,-,(,)]/g, ''); -- Replacing special characters with null
var FinalNo = telnot.replace(/\-+/g, ''); -- Getting Final Numbers
------------------Trimming Text For Title-----
var trim1 = this.nodeValue.replace(/\s/g, '');
var trim2 = trim1.replace(/\d+/g, '');
var trim3 = trim2.replace(/[:,-,(,)]/g, '');
var trim4 = trim3.replace('-', '');
var FinalTitle = "'" + trim4 + "'";
-------------------Matching Phone Numbers which you want to be act as a dialer---------------
if (FinalNo === '8002730713' || FinalNo === '8005100514') {
anchor.setAttribute('href', "tel:" + FinalNo);
var TitleLength = trim4.length;
if (TitleLength > 22) -------------- Minimizing text to be shown on title
{
return false;
}
else
{
anchor.setAttribute('onclick', "ga('send', 'event'," + FinalTitle + ", 'Click');"); setting a tracking on click
}
}
--------------Appending to dom------------------
anchor.appendChild(document.createTextNode(this.nodeValue.match(regex)[0]));
if (this.nextSibling)
this.parentElement.insertBefore(anchor, this.nextSibling);
else
this.parentElement.appendChild(anchor);
this.nodeValue = this.nodeValue.replace(regex, '');
}
return this.nodeType == 3;
});
});
</script>
-------------------------------------------------------------------------------------------------------------------------------
0 comments:
Post a Comment