Elio Chamy
Elio Chamy

Reputation: 269

Bootstrap sidebar navbar save opened tab after refresh

I have in my bootstrap website a side menu using bootstrap css class:

<div class="page-sidebar navbar-collapse collapse sidebar-nav">

<ul>
<li>
..
</li>
</ul>
</div>

if the user clicked on a tab, and the page refresh, how can I save the opened tab by the user? any idea?

Upvotes: 0

Views: 689

Answers (1)

ayinloya
ayinloya

Reputation: 134

  1. if you're using angular ui router, you can use the stateparam, if not there are other two options

  2. url params,

  3. localstorage,

for the second point

    function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


 url with param page ?tab=home
$scope.tab = getParameterByName('tab'); // this is called in the controller if the page is reloaded

###Edit### Then your add the param to your links

<li ng-class="active: tab === 'home' href="someurl/?tab=home"></li>
<li ng-class="active: tab === 'about' href="someurl/?tab=about"></li>

for the third option you can add ng-click with function

$scope.setTab = function(tab){
    $window.localStorage.setItem("tab", tab);
}

you can get the tab by

$window.localStorage.getItem("tab");

You'll have to handle null if the tab value is empty

You can use sessionStorage this is temporal

 set value 
 sessionStorage.tab = "home"
  get value
  $scope.tab = sessionStorage.tab

Upvotes: 2

Related Questions