Update amount of like / deslike with JQuery

-1

I'm trying to update the value of a span element (increase or decrease) whenever the like button is clicked.

Important: The following code creates another element only with the id #unlikeBtn instead of #likeBtn when the button is clicked.

_create: ->
      self = this
      $(@element).css('display', 'block').css('width','100%').css('height', '36px').removeClass('like-button').addClass('like-button-widget')
      @templates =
        notLiked: '''
          <a href="{{resourceUrl}}/like" id="likeBtn" class="{{cssClass}} like-button like-icon notliked">
            </a>
        '''
        liked: '''
          <a href="{{resourceUrl}}/unlike" id="unlikeBtn" class="{{cssClass}} like-button like-icon liked">
            </a>
          '''

I want to update the count value automatically every time the user clicks the button to enjoy or discard, but the function only works the first time. If I get deslike then it does not work. Only when I refresh the page and click to retrieve the value is updated.

$(window).load(function() {

  $('#likeBtn').click(function() {
    $('#likesCounter').html(function(i, val) { return val*1+1 });
  });

  $('#unlikeBtn').click(function () {
    $('#likesCounter').html(function(i, val) { return val*1-1 });
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="like-button-widget" style="display: block; width: 100%; height: 36px;">
<a href="#" id="likeBtn" class="btcupon like-button like-icon liked">
  click</a>
</div>
<span id="likesCounter" style="font-size: 16px; color: #6e6e6e; font-weight: 600;">1</span>

How do I always refresh without having to refresh the page?

    
asked by anonymous 13.03.2017 / 15:35

1 answer

0

Dynamically loaded elements do not accept the addition of a listener directly. Add the same to the parent element, or any other fixed on the screen as follows:

 $("body").on("click", "#Seuelemento" function(){
     //Faça o que quiser
})
    
13.03.2017 / 21:38