So I am trying to combine the answer of three questions posted here on stackoverflow; Save current state after jquery click function, Save data to local storage, and HTML5 local storage save .toggleClass. What I want to do is toggle between two classes onclick
using .one()
from jQuery. Then after the classes are toggled.
I would like to save the last added class. My code so far is as following:
jQuery
$(".post-tag").one('click', function() {
$(this).find('i').toggleClass('fa-meh fa-smile-beam text-warning text-success');
var likeState = $(this).find('i').hasClass('fa-smile-beam');
localStorage.setItem('liked', likeState);
var likedStorage = localStorage.getItem('liked');
if(likedStorage && $(this).find('i').hasClass('fa-smile-beam')) {
$(this).find('i').removeClass('fa-meh')
}
});
HTML
<div class="post-tag-wrapper">
<div class="post-tag shadow">
<i class="far fa-meh text-warning"></i>
</div>
</div>
How can I achieve this?
Heads up: I know it's doable if I add the class into a
Field
in theObject
; if usingMongoDB
for instance; having default asfa-meh
andonclick
using someAJAX
will update theField
in theObject
tofa-smile-beam
. But it's required usingLocalStorage
.Note: According to MDN, LocalStorage violates policy decision, so it's not the practice to save user interaction.