Search code examples
jqueryruby-on-railsturbolinks

Class disappears from element after page:load or change


I want to add a class to an li element on click to indicate that it is the current element.

this is the listener I was using

$(document).on("click",".sidebar ul li a",function(){
  if (!$(this).parent().hasClass("current")) {
    $("li.current").removeClass("current");
    $(this).parent().addClass("current");
  } 
});



But then I realized that the class gets added, and oups the page gets loaded again and the class disappears.

So I made use of page:load and page:change. And this is what I used :

$(document).on('page:change', function(){

  $('.sidebar ul li a').click(function() {
    $(this).parent().siblings().removeClass('current');
    $(this).parent().addClass('current');
  });

});

But I don't seem to pick the right thing.

Now I need help to add the class to the element and still have it after reload or page change. PS : More information

My manifest file

//= require jquery
//= require jquery.turbolinks
//= require current 
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks

Current is where I have the code I am using for this particular action.


Ruby on Rails
Jquery-railties 3.1.3
Turbolinks
jQuery-turbolinks


Solution

  • Actually I'm afraid you can't keep any javascript variables, states or events surviving page loads / changes. You would have to store them in cookies/localstorage/etc., parse them from your new link-url or set them server-side. An alternative would be not to completely reload the page and only for example reload the main content via ajax, replace it and set your navigation link class. If you plan on this you should also take a look on HTML5 History API and PushState in order to change your Urls according to your links.