I have photos with a button to Hide/Show photo. what is needed is as follow: If I press hide and refresh the page, the photo will remain hidden. I believe that is done by localStorage but I need help.
int index=0;
foreach (var item in Model.AttachmentsList)
{
<div style=" display: inline-block;">
@if (item.FileUrl.Contains(".jpg"))
{
@Html.Raw("<a href='../../" item.FileUrl "' alt='img'> <img id='photo_" index "' src='../../" item.FileUrl "' > </a>")
}
else
{
@Html.Raw("<a href='../../" item.FileUrl "' target='_blank'>" item.FileName "</a>")
}
</div>
<button onclick="togglePhoto(@index)">Hide/Show Photo</button>
index ;
}
here is js:
<script>
function togglePhoto(index) {
var photo = document.getElementById('photo_' index);
if (photo.style.display === 'none') {
photo.style.display = 'block';
} else {
photo.style.display = 'none';
}
}
CodePudding user response:
Update the localStorage whenever a photo is toggled, and run a function initPhotos
in
<body onl oad="initPhotos()">
that hides the hidden photos whenever the page is (re-)loaded.
function togglePhoto(index) {
var hiddenPhotos = JSON.parse(localStorage.getItem("hiddenPhotos") || "{}");
var photo = document.getElementById('photo_' index);
if (photo.style.display === 'none') {
photo.style.display = 'block';
delete hiddenPhotos[index];
} else {
photo.style.display = 'none';
hiddenPhotos[index] = true;
}
localStorage.setItem("hiddenPhotos", JSON.stringify(hiddenPhotos));
}
function initPhotos() {
var hiddenPhotos = JSON.parse(localStorage.getItem("hiddenPhotos") || "{}");
for (var index in hiddenPhotos) {
var photo = document.getElementById('photo_' index);
photo.style.display = 'none';
}
}