Sometimes if you are a blog or forum owner you need to make all your text (in URL format) turn into a live URL (clickable) to make it easier for your visitors to visit the link inside that content rather than manually copying that link and pasting it in the address bar. It’s hard if you change all your content one by one to make the links clickable.
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 a 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 non-commercially. And if you like it, please leave me a comment or say thanks in the comment box below, it means so much to me. At least it cheers me up to continue making snippet code to share with you.
