Let's get it out of the way now. Yes, the "Add to Favorites" button is pretty old-school. The modern web user is savvy enough to be able to quickly identify and use their web browsers bookmarking feature without much struggle.
But how many of us simply forget to bookmark a page or tool that we'd like to reference often? Having a small, intelligent, unobtrusive reminder to bookmark the page isn't going to force any visitors into a steaming fit of rage.
This is an okay practice, if used sparingly and appropriately:
- Don't place an "Add to Favorites" button on your home page, it should be reserved for deep links that the user might have difficulty locating again.
- Only display the link if JavaScript is available (since JavaScript is required to add the favorite to the browser).
- If a user has added the page to their bookmarks or favorites, don't display the link or icon to do so.
The first one is simple, just don't do it! The second one makes us think about implementation. For obvious reasons, the browser does not expose the current user's bookmarked pages in a request header or to JavaScript. So, how can we find out if the user has added our page as a favorite.
The short answer is, we can't. But, we can get close. By leveraging HTML 5 Storage, we can track when a user has clicked the "Add to Favorites" button in a local storage variable. With each page load, we'll check this variable to see if it contains the current page. If it does, we do not display the "Add to Favorites" button.
You'll notice in the code below that the bookmark "button" is added via JavaScript to the end of the <h1> tag. You can, of course, append it wherever you like. The purpose of this line is to demonstrate item #2 in the list above. We don't want this button to display if JavaScript is not available.
jQuery Add Bookmark Code
var page = location.href.replace(location.hostname, '').replace('http://', '').replace('https://', '');
if (typeof Storage !== 'undefined') {
if (window.localStorage.getItem('bmarkAttempt')) {
if (window.localStorage.getItem('bmarkAttempt').indexOf(page) !== -1) {
return false;
}
}
}
$('h1').append('<a id="bookmark"><img src="/mybookmarkimage.jpg" alt="Add to Fav\'s" /></a>');
$("#bookmark").click(function() {
BookmarkApp.addBookmark(this);
if (typeof Storage !== 'undefined') {
var bmarkAttempt = '';
if (window.localStorage.getItem('bmarkAttempt')) {
bmarkAttempt = window.localStorage.getItem('bmarkAttempt');
}
window.localStorage.setItem('bmarkAttempt', bmarkAttempt + ',' + page);
}
$(this).remove();
});
You'll notice the use of a function called BookmarkApp. You can copy/paste the code for this function from the creator's website at: http://eureka.ykyuen.info/2011/07/21/javascript-add-to-bookmark
However, you'll need to change one line of the code to function with IE.
Change:
var isMSIE = (-[1,]) ? false : true;
to
var isMSIE=(navigator.appName=="Microsoft Internet Explorer")?true:false;