here is the javascript code for preventing redirect when user clicks on a html anchor

javascript:

var url = {};

function addEvent(el, type, evt){
	if(el){
	if ( document.addEventListener ) {
	el.addEventListener( type, evt, false );
	} else if ( document.attachEvent ) {
	type="on"+type;
	el.attachEvent( type, evt );}}
}

function log4link0(el){
	addEvent(el, "click", function(evt){
		var lv = el.getAttribute("href");
		if(lv){
			/* record the clicked href */
			console.log("going to:"+lv);
			url.value = lv;}
		/* stop click event */
		if(evt){
			if (evt.stopPropagation ){
				evt.stopPropagation();
				evt.preventDefault();  
			}else{
				window.event.cancelBubble = true;
				window.event.returnValue = false;}
		}	
	});
}

function log4link(){
	var lks = document.getElementsByTagName("a");
	if(lks){
		var i=lks.length; while(i--){
			log4link0(lks[i]);}}
	/* register click event to element*/
	addEvent(document.getElementById("goto"), "click", function(){
		if(url && url.value)
			window.location = url.value;
	});
}

/* registr event on document load */
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", log4link, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){ 
		if ( document.readyState === "complete" ) {log4link();}
});}

html:

<body>
<a href="http://www.google.com">Google</a>
<a href="http://www.yahoo.com">YAHOO!</a>
<a href="http://www.baidu.com">Baidu</a>
<a id="goto">continue</a>
</body>

i also “componentlized” this into a light-weight and independent javascript js library, called Go2Later

Advertisements