Your code is correct, but when you click the tabs, it may seem like the menu is toggling again because new pages are being loaded. Each page starts fresh with the menu closed since HTML requests are stateless and don't retain information about the previous page's open menu.
To work around this issue, you can record the open state of the panel (using a cookie or URL parameter) and check that value on each page load, or use Ajax to load only the necessary parts of the page (preferred).
Implementing the Ajax solution transforms your website into a Single Page Application (SPA), ensuring that the JavaScript running on the page is preserved.
The following example demonstrates adding a handler for the menu link. It captures the clicked link's href attribute and uses it to fetch the new page content using $.get()
. The extracted content section of the page is then replaced within the existing page content div.
$('#sidebar a').click(function(e){
e.preventDefault();
// Load the target URL using Ajax
var href = $(this).attr("href");
$.get(href, function(html){
// Extract the content portion of the loaded page
var content = $(html).find('.content');
$('.content').replace(content);
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/f51k7eev/3/
Notes:
- I updated your load handler to use a DOM ready handler, which is recommended for jQuery as it ensures the script runs after the DOM is fully loaded.
- I removed unnecessary
parseInt
calls as jQuery's .width()
returns a pixel value without the "px" suffix.
Issues: If you pursue the SPA approach, remember to update the browser address bar URL manually (e.g., using history.js) to avoid always returning to the initial page upon refresh.