Home > database >  Rails how to remember the navbar status between clicks?
Rails how to remember the navbar status between clicks?

Time:05-18

I have a rails app with a nice navbar that can fold and unfold. The navbar contains links that point to different controllers and actions.

Every time a user clicks on one of the links, the browser goes to the new page and the navbar gets reset to its initial state.

I need to maintain the fold/unfold status of the navbar between calls (that is better user experience).

I'm not sure how to do so.

I thought to add in the javascript that handles the folding a URL parameter so that the next view can dig it and load the menu in the previous state. This parameter would be completely handled in the view, so no changes in the controllers.

I'm not sure this is the best way to approach this.

I've been suggested to use the session object. but I think that this will still require some sort of passing params (still via URL), and would require changing the controllers (there are many, I'm not very happy to change them all and after all this is a purely user interface matter).

Would it be reasonable to use the window.local/session storage for this?

any suggestions?

CodePudding user response:

You could have a boolean in your database that gets updated every time the user clicks a link in the navbar and then redirect to the appropriate view.

The view decides which status of the navbar to show (folded or unfolded) based on the value of the boolean.

CodePudding user response:

In the end I went for using localStorage,

It was rather simple to implement, and it's a purely JS solution, the only side effect is that when the page load there's an extremely fast flicker when the navbar is open (the navbar is loaded closed, then JS opens it).

the code just runs down to these few lines of code:

$('.chevrons .open').click(function(event) {
    localStorage.setItem('navbar', 'open')
    ....
});

$('.chevrons .close').click(function(event) {
    localStorage.setItem('navbar', 'closed')
    ....
});

if (localStorage.getItem('navbar') === 'open') {
    $('.chevrons .open').trigger('click')
}
  • Related