rubhan rubhan - 2 years ago 135
Javascript Question

rails page navigation through side menu bar

I am working on an application and here I have a side menu bar (image is attached here)here is the link of screenshot.

what I want is to navigate through this menu, actually I want this menu to be preset on every page mentioned in menu list. And also there should be focus on link on which I am currently on. here I have attached screenshot of that too.

I was thinking to repeat my side nav menu code on all the pages on menu. But It won't active/focus the currently active link. Any better solutions? What should I do to solve this issue?

Answer Source

You can put your menu in a partial. Lets call it _sidebar_menu.html.erb

Then you load it in every page OR in your application.html.erb like this ->

<%= render partial: "layouts/sidebar_menu" %> Replace "layouts" with any folder inside which you've kept your menu file.

So now you've the menu appearing in every page. You can "select" the menu or add your defined class to make it "active" by using some javascript. One way is to check for the url, and make the respective link active, OR you can use your rails controller and action's name to determine which link to activate.

    controller_name = "<%= params[:controller] %>"
    //The controller name will be dynamically inserted by rails
    $(".sidebar-menu li a").each(function(){
        if($(this).attr("href").toDownCase().indexOf(controller_name) > -1){

I am assuming your url has the controller's name in it. You can also use your controller's action name, like <%= params[:action] %> in order to achieve it. You can play around with it to find the solution that helps in your case. I hope you get the idea. Let me know if it worked.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download