Question

I am pretty new to JQuery and I'm working on a menu based on Superfish script. I am having troubles to keep the addClass on current clicked item set when I navigate thru links.

My code:

JS

<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){

jQuery("ul.sf-menu").superfish({pathClass:  'corrente'});            

jQuery('#sf-menu li a').click(function() {
      jQuery("#sf-menu li").removeClass('corrente');
      jQuery(this).parents().filter("li").addClass('corrente');
      jQuery("ul.sf-menu").superfish({pathClass:  'corrente'    });
});
});
</script> 

HTML

<ul id="sf-menu" class="sf-menu sf-navbar">
  <li><a href="#">Home</a></li>
  <li><a href="#">Band</a></li>
  <li><a href="#">Solo Projects</a>
      <ul>
      <li><a href="#">Tim</a></li>
      <li><a href="#">Tom</a></li>
      <li><a href="#">John</a></li>
      </ul>
  </li>
  <li><a href="#">Media Appearances</a></li>
  <li><a href="#">Tour</a>
      <ul>
     <li><a href="#">The Reunion Tour</a>
         <ul>
        <li><a href="#">North American Leg</a></li>
     </ul>
         </li>
      </ul>
  </li>
  <li><a href="#">Gallery</a></li>
</ul>

The above html works fine, the class "corrente" is correctly set, but when I change html inserting actual links, the class is set fine but get lost when the destination page is loaded.

Can you please give me any advice on how store the class added and pass it thru the destination page?

Thank you in advance

Was it helpful?

Solution

The entire Javascript environment resets when you go to a new page, so you can't keep changes made in javascript between pages.

Possible ways to deal with this:

  1. open the new page in an iframe or in a separate window. The outer page (for an iframe) or the original page (for a separate window) doesn't reload, so javascript changes in it will not be lost.
  2. Add some sort of querystring to the url when you pass to the new page, and then interpret that querystring in the new page (within javascript) to make whatever change you've made again.
  3. Put data in a cookie that will allow you to apply the change on the new page.

OTHER TIPS

If it still helps, I use a jQuery plugin called jquery.cookie.

In my case I was working with WordPress and a plugin for a Quiz, after each step the page reloaded and I lose my modifications.

So, after I setup the jquery.cookie plugin I was able to keep the jQuery modifications, like adding classes or removing them.

you could

  • store the class added in a cookie
  • make an AJAX request back to the server to persist the state on the server (perhaps in a datasource, such as a database)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top