Jonathan
Jonathan

Reputation: 683

Rails Bootstrap Active class with ordering

I'm trying to implement the bootstrap active class to my navigation links but currently it's not working with my ordering in rails. The class is supposed to be applied when the clicked link matches the current URL.

This is the URL when the ordering is set

http://localhost:3000/posts?order=hot

But it's not actually applying the active class, as I'm guessing it's the '?' that's breaking it.

var url = window.location;
// Will only work if string in href matches with location
$('.sorting ul li a[href="'+ url +'"]').parent().addClass('active');

This code doesn't seem to be working with the '?'. From this question here

Upvotes: 0

Views: 120

Answers (1)

Matthew Higgins
Matthew Higgins

Reputation: 608

As you're reloading the whole page (as mentioned in the comment), you could skip the Javascript altogether, and do something in the view like (HAML example, let me know if you need an ERB example);

%li
  %a{href: '#', class: "#{'active' if params[:order] == 'hot'}"} 
    Link text here

This will read the GET parameter (?order=) from the URL, then add the active class to this a tag, if it is set as hot.

The Javascript example in the Bootstrap docs is how you would do it if you were dynamically updating the content.

Edit: and here's the untested ERB version;

<li>
  <a href="#" class="<%= if params[:order] == 'hot' %>active<% end %>">
    Link text here
  </a>
</li>

Upvotes: 1

Related Questions