fradrive/static/js/utils/showHide.js
2019-02-16 17:23:52 +01:00

56 lines
1.6 KiB
JavaScript

(function() {
'use strict';
window.utils = window.utils || {};
var LOCAL_STORAGE_SHOW_HIDE = 'SHOW_HIDE';
/**
* div
* div.js-show-hide__toggle
* toggle here
* div
* content here
*/
window.utils.showHide = function(wrapper, options) {
function addEventHandler(el) {
el.addEventListener('click', function elClickListener() {
var newState = el.parentElement.classList.toggle('js-show-hide--collapsed');
updateLSState(el.dataset.shIndex || null, newState);
});
}
function updateLSState(index, state) {
if (!index) {
return false;
}
var lsData = fromLocalStorage();
lsData[index] = state;
window.localStorage.setItem(LOCAL_STORAGE_SHOW_HIDE, JSON.stringify(lsData));
}
function collapsedStateInLocalStorage(index) {
return fromLocalStorage()[index] || null;
}
function fromLocalStorage() {
return JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_SHOW_HIDE)) || {};
}
Array
.from(wrapper.querySelectorAll('.js-show-hide__toggle'))
.forEach(function(el) {
var index = el.dataset.shIndex || null;
el.parentElement.classList.toggle(
'js-show-hide--collapsed',
collapsedStateInLocalStorage(index) || el.dataset.collapsed === 'true'
);
Array.from(el.parentElement.children).forEach(function(el) {
if (!el.classList.contains('js-show-hide__toggle')) {
el.classList.add('js-show-hide__target');
}
});
addEventHandler(el);
});
};
})();