Update amount of like/deslike with Jquery

Asked

Viewed 95 times

-1

I am 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 on the button to like or excuse, but the function only works the first time. If I give slide then it does not work. Only when I refresh the page and click to disregard 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>
<div class="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 update without having to refresh the page?

  • Running your code on the Stack Overflow website is working.

  • What happens is that there is a piece of code missing in coffescript that creates another element with the id #unlikeBtn, but if I click a second time on that button the value of the count does not decrease.

  • You could post the code that’s missing?

  • I will update the question.

  • Adding events to dynamically created elements doesn’t really work. I’ve suffered enough with it. Add the event to a fixed element and focus on the dynamic: so $(body). on('click", "#elementtal", Function());

  • Dude I don’t understand your question, it’s working

Show 1 more comment

1 answer

0

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.