Search code examples
javascriptimagefunctionbookmarks

Compare localStorage keys with any element id and add class to element if equals


I'm trying to build a bookmark / favorite function for a picture gallery, so that a user can mark certain pictures as favorites (saved to the localStorage).

So, currently I do call a function on every element via onClick="addFavorites(this)" and the function is

function addFavorites(element) {
    var bild = element.id;
    if (localStorage.getItem(bild) === null) {
        localStorage.setItem(bild, bild);
    } else {
        localStorage.removeItem(bild);
    }
}

This works fine so far. Now I'd like to have the selected pictures also visually been marked (especially on page reload) and I'm doing hard to find a solution on that. Is there a possibility to compare the localStorage keys with any element id and add a class f.e. favorite to element if it equals.

Maybe there's also an easier way to get this solved?

Any help or ideas would be great!


Solution

  • Let's say your pictures all have an identifying class, like "picture". Then you could have something like this run on page load:

    var pictures = document.querySelectorAll(".picture");
    pictures.forEach(picture => {
        if (localStorage.getItem(picture.id)) {
            picture.classList.add("favorite");
        }
    });
    

    You would also need to change your addFavorites slightly:

    function addFavorites(element) {
        var bild = element.id;
        if (localStorage.getItem(bild) === null) {
            localStorage.setItem(bild, bild);
            element.classList.add("favorite");
        } else {
            localStorage.removeItem(bild);
            element.classList.remove("favorite");
        }
    }
    

    And then, of course, you would manage the appearance of the favorite class in your CSS styles.