Add to Favorite using JavaScript



Bookmark feature of the browser is very useful, when we need that page in future. Sometimes we found an important web pages, that might be useful in future, so we used to bookmark this on the browser. So today in this article I am showing you how to add to favorite using JavaScript.

To add to favorite I have created a JavaScript function addToFavorite() as follow:

function addToFavorite(title, url){
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
		window.sidebar.addPanel(title, url, "");
	} else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} else if(document.all){ // ie
		window.external.AddFavorite(url, title);
	} else {
		alert(withKeys());
	}
}

In some cases the function could not bookmark the page so I have used another function withKeys() to show an key press option to add to favorite the page.

function withKeys() {
	var ua = navigator.userAgent.toLowerCase();
	var str = '';
	var isWebkit = (ua.indexOf('webkit') != - 1);
	var isMac = (ua.indexOf('mac') != - 1);
	var isGecko = (ua.indexOf('gecko') != - 1);

	if (ua.indexOf('konqueror') != - 1) {
		str = 'CTRL + B'; // Konqueror
	} else if (window.home || isWebkit || isMac || isGecko) {
		str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab, IE5/Mac
	}
	return ((str) ? 'Press ' + str + ' to bookmark this page.' : str);
}

Now we can use above function like below:

<a href="javascript:void(0)" onClick="addToFavorite('Tricks Of IT', 'http://www.tricksofit.com')">Add to Favorite</a>

I hope this will help you to add to favorite using JavaScript.

LIVE DEMO