Search code examples
jquerybuttonincrementdecrement

How to makelike button with once click +1 value, second click -1 value etc


I am new here

I have this code

<div class="like-buttons">
    <div class="liked"></div><button class="dislike like"><span class="countl">12</span></button>
</div>

https://codepen.io/Void0000/pen/oNzGmGr

and I need to make (with jQuery) some function, that when I will click on my button, it will be count +1 (eg: if it was 2 it becomes 3), and when I click again on it, it will count -1 (eg: if it was 3 it now becomes 2) and etc.


Solution

  • According to @Shivam 's answer you can change like this;

    $('.like').onclick(function(){
         let like = $(this).closest('.countd').html();
         if($(this).hasClass("clicked")){
             $(this).removeClass("clicked");
             like++;
         }
         else{
             $(this).addClass("clicked");
             like--;
         }
         $(this).closest('.countd').html(like)
    });
    

    Can you check this Link. I made some changes.

    $(document).ready(function() {
       $('.like').click(function() {
           let like = parseInt($('.countl').html());
           if ($(this).hasClass("clicked")) {
               $(this).removeClass("clicked");
               like++;
           } else {
               $(this).addClass("clicked");
               like--;
           }
           $('.countl').html(like)
       });
    });