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