A simple javascript HTML5 link replacement function.

A client needed an alternate way of creating links due to a translating tool breaking all links it translated. I suggested a solution using HTML5 custom data attributes with JavaScript. Basically what i’m doing is adding a new data-href attribute to hyperlinks that need to be ignored by the translation system. I am then triggering the link with a jQuery bind event then stopping the original link from triggering with javascript. I’ve tested the code and it should work in IE7.

A normal link

This is a normal link. The markup looks like this:

<a href="https://www.google.com.au/">Google</a>

Here is a normal functioning link using a traditional href attribute: Google

Alternate link

This is the alternate link using custom data attributes which the translation system should ignore.

The mark up looks like this:

<a href="# "data-href="https://www.google.com.au/">Google</a>

This is the new link using the new custom attribute tag: Google

Mark up:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		alternateLink.init();
	});
	var alternateLink = {
		init: function(){
			$('a[data-href]').bind('click', function(){
				var a = $(this).attr('data-href');
				window.location.href=a;
				return false;
			});
		}
	}
</script>