Menubar with current active without reloading page

32 views
Skip to first unread message

Oliver Wittwer

unread,
Dec 1, 2018, 12:37:54 PM12/1/18
to intercooler-js
Hi there

I plan to create an app using an admin template with a sidebar menu. Instead of loading a page when clicking on a menu item I'd like to realize this using intercooler and not realoding the whole page but only the main content. Has someone an idea how to do this?

Typically the menu will be structured like this: 

<ul class="menu-list">
    <li class="menu-item active" ic-get-from="/page-1" ic-target="#main-content">Menu Item 1</li>
    <li class="menu-item" ic-get-from="/page-2" ic-target="#main-content">Menu Item 2</li>
    <li class="menu-item" ic-get-from="/page-3" ic-target="#main-content">Menu Item 3</li>
</ul>

Now I would need something like ic-add-class and ic-remove-class to the clicked item and all the other menu items accordingly to add/remove the class="active". 

How would I do that? 

Regards,
Oliver

Anders Baumann

unread,
Dec 3, 2018, 9:35:27 AM12/3/18
to intercooler-js
Hi Oliver.

I have implemented this. On each menu item I have the following attribute:
ic-on-complete="updateSelectedMenuItemInHeader('#navbar-frontpage');"

The JavaScript is very simple:
function updateSelectedMenuItemInHeader(selected) {
$('#navBar').find('a.active').removeClass('active');
$(selected).addClass('active');
}

If you use "ic-push-url='true'" then you need to also handle the "Back" button. Like:

$(window).on('popstate', function (event) {
updateSelectedMenuItemOnBackButton(event);
});

function updateSelectedMenuItemOnBackButton(event) {
if (typeof Storage === "undefined") return;
var stateData = event.originalEvent.state;
if (stateData === null) return;
var historyData = JSON.parse(localStorage.getItem(stateData['ic-id']));
if (historyData === null) return;

// Home
if (historyData.url === '/xyz' || historyData.url === '/xyz/') {
updateSelectedMenuItemInHeader('#navbar-frontpage');
return;
}
   ....
}

I hope this helps.

/Anders
Reply all
Reply to author
Forward
0 new messages