For example, I have some items whose status is completed and they have class completed
<body onload="loadItem()">
<ol class="list-group">
<li class="list-group-item completed" id="item-1">Text1</li>
<li class="list-group-item completed" id="item-2">Text2</li>
</ol>
</body>
Also, there are two buttons
<button type="button" onclick="showItem();" class="btn btn-outline-primary">Show completed</button>
<button type="button" onclick="hideItem();" class="btn btn-outline-primary">Hide completed</button>
And JavaScript functions
function hideItem() {
var targList = document.getElementsByClassName("completed");
var hidden_ids = []
for (var x = 0; x < targList.length; x++) {
targList[x].setAttribute('style', 'display: none !important');
hidden_ids.push(targList[x].id)
}
localStorage.setItem("autosave", JSON.stringify(hidden_ids));
}
function loadItem() {
var hidden_ids = JSON.parse(localStorage.getItem("autosave") || '[]');
for (var x = 0; x < hidden_ids.length; x++) {
document.getElementById(hidden_ids[x]).setAttribute('style', 'display: none !important');
}
}
function showItem() {
var targList = document.getElementsByClassName("completed");
var hidden_ids = []
for (var x = 0; x < targList.length; x++) {
targList[x].setAttribute('style', 'display: flex');
hidden_ids.push(targList[x].id)
}
localStorage.setItem("autosave", JSON.stringify(hidden_ids));
}
But, it does not work. On page reload it only hides completed items. However, I want it to be shown as default and if I press Hide button, it should be hidden even after page reload
Instead of storing id's, you might be use this solution maybe? If I understand your question correctly, it might be help.
function loadItem() {
if (localStorage.getItem('hide')) {
hideItem()
}
}
function showItem() {
localStorage.removeItem('hide')
document.querySelectorAll('.completed').forEach(li => li.style.display = 'list-item')
}
function hideItem() {
localStorage.setItem('hide', true)
document.querySelectorAll('.completed').forEach(li => li.style.display = 'none')
}