Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Like button - Toggle between two functions

I'm trying to toggle between two functions when a "Like" button is clicked.

 <div class="like">
  <div class="count"><%= post.num_likes %> </div>
  <div class="icon" id="like"><i class="icon-thumbs-up-alt"></i></div>
</div>      

right now I have:

$(".like").click(function(event){       
event.stopPropagation();                    
$("i", this).toggleClass("icon-thumbs-up-alt").toggleClass("icon icon-thumbs-up");                           
 likePost(TestCanvas, $(this).prev('div').find('.hideThis').text());    
 });

likePost(canvasID, postID) takes parameters and interacts with an API When I click on .like again, I would like to call unlikePost().

Is there an easy way to toggle between likePost() and unlikePost() when .like is clicked?

Ive tried:

$('.like').toggle(function() {
 alert('First handler for .toggle() called.');
 likePost(TestCanvas, $(this).prev('div').find('.hideThis').text());
}, function() {
alert('Second handler for .toggle() called.');
unlikePost(TestCanvas, $(this).prev('div').find('.hideThis').text());
});

Its not working as i thought it would though. Seems to execute on page load instead of on click of .like.

like image 889
Anthony Avatar asked Jul 01 '13 19:07

Anthony


2 Answers

Toggle a class. Than by reading if the element has such class - you can deduce if the user liked or removed it's like:

$('.like').click(function() {
  var val = parseInt($(this).text(), 10);
  $(this).toggleClass('is-liked');
  
  if ($(this).hasClass('is-liked')) {
    val++
    // User has liked (insert userId, itemId into Likes table)
  } else {
    val--
    // User removed his like (delete from table Likes where userId and itemId)
  }
  
  $(this).text(val);
});
.like {
  font: 14px/1.4 sans-serif;
  display: inline-block;
  padding: 3px 10px;
  cursor: pointer;
  box-shadow: inset 0 0 0 2px #0bf;
  font-weight: bold;
  user-select: none;
}
.like:after {
  content: "👍";
  vertical-align: top;
  margin-left: 5px;
}

.is-liked {
  background: #0bf;
  color: #fff;
}
<span class="like">0</span>
<span class="like is-liked">3</span>
<span class="like">6</span>
<span class="like">12</span>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
like image 158
Roko C. Buljan Avatar answered Oct 27 '22 18:10

Roko C. Buljan


You can add a "liked" class when liked.

$('.like').on('click', function() {
  if $(this).hasClass("liked") {
    //do unlike
    $(this).removeClass("liked");
  }
  else {
    //do like
    $(this).addClass("liked");
  }
});
like image 39
Smeegs Avatar answered Oct 27 '22 19:10

Smeegs