Solution 1 :

Well you could add something like this at the start of the “click” handler:

$(“.reaction-post”).removeClass(“dislike like”);

This will, on a like/dislike button click, remove all “like” or “dislike” class to your .reaction-post, and then your script applies a new one depending on the clicked button.

Note: if you have many elements like this on your page (DOM) (many like and dislike button), you may want to restrict the class manipulation to the clicked element.

Edit: your code could look like this (not tested, but you get the idea):

<script>
$(function(){
    $('.reaction-post div').click(function(){
        var likable_element = $(this).parent(); //the .reaction-post, easier to manager multiple likeable element on the same page
        likable_element.removeClass("dislike like");
        
        var lod = $(this).attr('data-title');
        var idr = likable_element.attr('data-id');       
        localStorage.setItem(idr,lod);
        var ratinghis = localStorage.getItem(idr);
        likable_element.addClass(ratinghis);     
    });
});
</script>

Problem :

I’m trying to generate a jQuery code with post review functionality. What I want to create looks like the image below:

enter image description here

Like and dislike buttons will be highlighted each time they are clicked. The reaction will be stored locally using localStorage.

This is my HTML code:

<div class="reaction-post" data-id="123456">
      <div class="like" data-title="like">Like</div>
      <div class="dislike" data-title="dislike">Dislike</div>
</div>

This is my jQuery code:

$(function(){
    $('.reaction-post div').click(function(){
        var lod = $(this).attr('data-title');
        var idr = $('.reaction-post').attr('data-id');       
        localStorage.setItem(idr,lod);
        var ratinghis = localStorage.getItem(idr);
        $('.reaction-post').addClass(ratinghis);     
    });
});

My problem is I don’t know how to removeClass after click to another option.

Comments

Comment posted by Thành Nan Nguyễn

Thank you, it worked. I still have a question as to whether my way of using localStorage can cause the evaluations to still be valid after the page reloads?

Comment posted by Mtxz

Yes, your values should still be in the LocalStorage after a refresh. Unless you update it somewhere else in-between.

By