Skip to content Skip to sidebar Skip to footer

Maintaining State In Javascript Through Html Class

I'm creating a web app in which users can bookmark certain places. For this I've created a span element which initially has a class no-bookmark. Whenever a user clicks this span e

Solution 1:

It isn't too bad way a to do it though it does mix logic with the UI which can be difficult to maintain long term.

One catch though. What happens if you submit a request (whether to set or delete the bookmark) and it fails? Then your class is out of step with reality.

You also need to remember that other things could change the CSS class. Any manner of client-side code could change the classes so be wary of that too.

Also what happens when the user closes the page and later reopens it? You still have to have another setting somewhere to track unless you don't care about longer-term state.

If you do care about long-term state, you could use cookies, local storage or indeed back-end storage to maintain that state depending on the design of your system. In that case, there is probably no benefit in trying to maintain the state purely in the class, it would be more robust to track state in a JS variable though the class is probably still useful but only for UI purposes.

You could look at something like REACT to help you with these things. At the cost of some initial load "weight", you get a LOT of help with maintaining state and being reactive.

Solution 2:

For this answer, I suppose that you have access to the server API, and that the state - some user ID and the bookmarked item, can be retrieved by the API anytime. If I'm not supposing correctly, stop reading now.

So the server, possibly by some database, always knows if a certain user, say user087 has currently item item118 bookmarked. I would get, when the list of <span>s has loaded, for each item, by ajax, a value of true/false for the given user id and item id, whether it's a bookmark or not. Then I'd set the appropriate style to the span.

This way you effectively separates logic from user interface, and you always have the correct state, as soon as the <span>s load, and independently of browser behavior.

EDIT

Following the asker's comment. Moreover, you can populate the loaded states to an object. An example of usage of such an object would be to count (and present) user's bookmarks total, or search for a bookmark if there is plenty, without having to ajax. So, between loads, you can have a temporary local database of your states.

Post a Comment for "Maintaining State In Javascript Through Html Class"