Reputation: 33
I currently have a jquery accordion that does exactly what I want, except for one thing. When I click on a link in the accordion panel to go to another page I would like the accordion to remain open at the same place (if possible) when I click the back button. The back button is an image that I've created and not the back button of the browser.
This is my jquery script:
<script>
$(function() {
$(".jquery-ui-accordion").accordion({
autoHeight: false,
collapsible: true,
heightStyle: "content",
active: false,
animate: 300 // collapse will take 300ms
});
$('.jquery-ui-accordion h3').bind('click',function(){
var self = this;
setTimeout(function() {
theOffset = $(self).offset();
$('body,html').animate({ scrollTop: theOffset.top - 100 });
}, 310); // ensure the collapse animation is done
});
});
</script>
This is what's in my header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
It opens and scrolls very nicely and if there's a long piece of text in a different accordion panel, the panel that was clicked on will jump into screen view.
I don't want to alter what it does currently, I just want to be able to add a remember state when I click the back button image.
I've read about jquery
cookies but honestly would not even know where to start with that to include it.
Any help would be greatly appreciated!
Upvotes: 1
Views: 2552
Reputation: 43166
You can make use of localStorage
as shown below:
$(document).ready(function () {
var selectedIndex = localStorage.getItem("selected"),
// If a valid item exits in localStorage use it, else use the default
active = (selectedIndex >= 0) ? parseInt(selectedIndex) : false;
console.log(active);
$(".jquery-ui-accordion").accordion({
active: active,
autoHeight: false,
collapsible: true,
heightStyle: "content",
animate: 300, // collapse will take 300ms,
activate: function (event, ui) {
if (ui.newHeader.length) // item opened
var index = $('.jquery-ui-accordion h3').index(ui.newHeader);
if (index > -1) // has a valid index
localStorage.setItem("selected", index);
}
});
$('.jquery-ui-accordion h3').bind('click', function () {
var self = this;
setTimeout(function () {
theOffset = $(self).offset();
$('body,html').animate({
scrollTop: theOffset.top - 100
});
}, 310); // ensure the collapse animation is done
});
});
Don't forget to check whether localStorage is supported or not before using it though. You fallback to cookies doing the same thing.
Upvotes: 1
Reputation: 115
You can create a flag and set it as true
when the accordian is clicked.
On clicking Back button, check if the flag is set as true or false. If it is set as true
, just trigger the click action for that selector.
$('.jquery-ui-accordion h3').trigger('click')
Upvotes: -2