I am trying to get links to execute javascript instead of the href attribute. I've scoured the web and can get close with several different methods, but no cigar.
Example conversions look like this:
<a href="http://example.com">Link 1</a>
<a href="http://www.yahoo.com" target="_blank" class="whatever">Link 2</a>
to something like:
<a href="#" onclick="OpenLink('http://example.com');return false;">Link 1</a>
<a href="#" onclick="OpenLink('http://www.yahoo.com');return false;">Link 2</a>
Examples of what I've tried:
- The content is dynamic so I tried replacing on the fly with JQuery, but it still executes the href AND the Javascript.
$("a[href*=.com]").live('click', function(event){
event.preventDefault();
var href=this.href;
// Modifications of the Attributes don't work here to disable/change href
openMe(href);
return false;
});
-I've also tried replace the links BEFORE the content is written to the page
$(input_content).find('a[href*=.com]').each(function(){
var href = this.href;
$(this).attr('href', 'javascript:openMe('+href+');');
// AND
$(this).closest('a').replaceWith("<a href='javascript:openMe("+href+");'>"+$(this).text()+"</a>");
});
-And lastly I tried to Linkify() but this only works for text urls, and leaves tags a mess:
function Linkify(inputText) {
var replaceText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://
replacePattern1 = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|">])/gim;
replacedText = inputText.replace(replacePattern1, '$1');
}
Does anyone have any suggestions in either Javascript/JQuery (or as a backfall PHP)? For something so seemingly simple, I just haven't been able to figure it out...
Much thanks in advace
Originally asked by: the_dillio on Stack Overflow


Answers