Start a new discussion

To start a new discussion please visit the discussions section of the GitHub home page of the project.

Discussions on GitHub

You can also search our old self-hosted forums for any useful information below but please note that posting new content here is not possible any more.

Reply To: Remember the sub-item selected

Home Forums Older releases 1.0.x Remember the sub-item selected Reply To: Remember the sub-item selected

#2731
admin
Keymaster

Hi and sorry for the delay of this answer!

There are different ways to achieve it but here is a simple client-side solution that uses window.localStorage which is supported in all latest browsers (better than cookies in our case since it’s not sent with every request). This needs to be called ondomready after the SmartMenus init code:

// save last selected item to localStorage
var $mainMenu = $('#main-menu'),
	localStorage = window.localStorage;
$mainMenu.bind('select.smapi', function(e, item) {
	if (localStorage) {
		// since the items (links) don't have static ids by default, we'll save the item's index
		// save a timestamp too
		localStorage.sm_lastSelectedItem = $mainMenu.find('a').index(item) + '-' + new Date().getTime();
	}
});

// restore last selected item
if (localStorage && localStorage.sm_lastSelectedItem) {
	// only restore if the menu is in collapsible mode on init
	if ($mainMenu.data('smartmenus').isCollapsible()) {
		var itemData = localStorage.sm_lastSelectedItem.split('-'),
			itemIndex = itemData[0],
			timeStamp = itemData[1];
		// restore the item if saved within the last 1 hour
		if (new Date().getTime() - timeStamp < 60 * 60 * 1000) {
			var $item = $mainMenu.find('a').eq(itemIndex);
			$mainMenu.smartmenus('itemActivate', $item);
			$item[0].focus();
		}
	}
	localStorage.removeItem('sm_lastSelectedItem');
}

The above will restore the last item if it was selected within the last hour. You can tweak the expiration period on this line if you like:

		// restore the item if saved within the last 1 hour
		if (new Date().getTime() - timeStamp < 60 * 60 * 1000) {

Let me know if you have any questions.

Cheers!