I've been brainstorming ways to add a toggle menu on my website and finally stumbled upon a solution that works great!
<div>
<h1><button class="button" data-circle="travel">
<i class="fa fa-plus-square"></i>
</button> Travel</h1>
</div>
<div class="travel options">
<ul>
<li>Travel</li>
<li>Vehicles</li>
</ul>
</div>
var localStorageKey = "app_state";
// keeping track of state
var default_state = {
biographies: false,
pictures: false,
poetry: false
}
var saved_state = localStorage.getItem(localStorageKey);
var state = saved_state ? JSON.parse(saved_state) : default_state;
$(function() {
init();
$('.button').on('click', function() {
var circle = $(this).attr('data-circle');
toggleCircle(circle, !state[circle]);
$(this).find('i').toggleClass('fa-minus fa-plus');
});
});
function init() {
for(var key in state) {
var is_displayed = state[key];
if ( is_displayed ) {
$(this).find('i').toggleClass('fa-minus fa-plus');
} else {
$(this).find('i').toggleClass('fa-plus fa-plus');
}
console.log(is_displayed);
toggleCircle(key, is_displayed);
}
}
function toggleCircle(circle, is_displayed) {
if (is_displayed) {
$('.'+circle).show()
state[circle] = true;
} else {
$('.'+circle).hide()
state[circle] = false;
}
localStorage.setItem(localStorageKey, JSON.stringify(state));
}
However, I noticed that when you minimize a menu and then refresh the page, the icon still shows a - even though it's already minimized. Is there a way to fix this issue?
I acknowledge that the code above is not original and unfortunately, I couldn't find the person to credit! My jquery skills are lacking.
Any assistance would be greatly appreciated.
Thank you