Snippet Code To Make Automatic Live URL With JQuery

Sometimes if you a blog or forum owner you need to make all your text (in url format) turn into a live url (clickable) to make your visitors easier to visit the link inside that content rather than manual copy that link and paste it in address bar. It’s hard if you change all your content one by one to make this link click able.

See the following example:

Text with url format (unclickable):

http://www.ivankristianto.com/search/regular-expression

Live link/url (clickable):

<a href="http://www.ivankristianto.com/search/regular-expression">http://www.ivankristianto.com/search/regular-expression</a>

 

So to change that text into live link, you can use the following JQuery:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script><script type="text/javascript">// <![CDATA[
jQuery.fn.textNodes = function() {
var ret = [];
this.contents().each(function() {
var fn = arguments.callee;
if(this.nodeType == 3) {
ret.push(this);
} else if(this.nodeType==1 &&!(
this.tagName.toLowerCase()=='script' ||
this.tagName.toLowerCase()=='head' ||
this.tagName.toLowerCase()=='iframe' ||
this.tagName.toLowerCase()=='textarea' ||
this.tagName.toLowerCase()=='option' ||
this.tagName.toLowerCase()=='style' ||
this.tagName.toLowerCase()=='title' ||
this.tagName.toLowerCase()=='a')){
jQuery(this).contents().each(fn);
}
});
return ret;
}

jQuery.fn.livelink = function() {
re_link2 = new RegExp('(https?://(?:[A-Z0-9].)*(?:(.*).(.*))[-()A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|])', "ig");
re_link3 = new RegExp('https?://(?:[A-Z0-9].)*(?:(.*).(.*))[-()A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]', "i");
this.each(function(i){
jQuery.each($(this).textNodes(), function(i, node){
text = node.nodeValue;
if(re_link3.test(text)){
newNode=document.createElement('span');
text=jQuery('
<div/>').text(text).html();
newNode.innerHTML=text.replace(re_link2, '<a href="$1" target="_blank">$1</a>');
node.parentNode.replaceChild(newNode, node);
}
});
});
}

$(function() {
$("div").livelink();
});
// ]]></script>

 

 

Or see the example, and to get the code you can view the source to copy it. This code is free to use commercially and noncommercial. And if you like it, please leave me a comment or say thanks at the comment box below, it means so much for me. At least to cheer me up to continue make snippet code to share with you.

Comments

  1. IToon says:

    thanks buddy….

  2. Anonymous says:

    nice info,keep posting

Give me your feedback

This site uses Akismet to reduce spam. Learn how your comment data is processed.