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.
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>
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With