node.js - Like button, add and subtract on database. nodejs, mongodb, mongoose, jquery -
i building website user can like, button working, storing likes on database. question is, how can make user when click button again, subtract on database. have animation of button, 1st default state is grey, when user click it, turn blue , "liked" text appear besides it. when user clicks again, go black.
here's code on post route (because adding data database)
app.post("/index/:id", function(req,res){ testdata.findbyid(req.params.id, function(err, theuser){ if(err){ console.log(err); } else { theuser.likes += 1; theuser.save(); console.log(theuser.likes); } }); });
my ejs file:
<a class="likeicon" href="/index/<%= newusers._id %>?_method=post"> <i class="fa fa-thumbs-o-up" aria-hidden="true" ></i> </a>
and jquery:
$(".likeicon").on('click', function(){ if($(this).css("color") === "rgb(0, 0, 255)"){ $("#likedtxt").remove(); $(this).css("color", "black"); $(this).animate({fontsize: "15px"}); } else { $(this).css("color", "blue"); $(this).append("<span id='likedtxt'>liked</span>"); $(this).animate({fontsize: "18px"}); } });
also question, when click liked, adding database, how can show live on user screen count on likes updated? without reloading screen. because dont want use res.redirect, refreshes webpage.
imo better can write onclick function "likeicon" button
<a class="likeicon" userid="<%= newusers._id %>" onclink="updatelikes()"> <i class="fa fa-thumbs-o-up" aria-hidden="true" > 49 </i> </a>
function:
function updatelikes() { id = $('.likeicon').attr('userid'); $.post('/index/' + id, function (response) { $('fa-thumbs-o-up').text(response.likecount); //your counter on page //and update likes counter response }) }
and node.js
app.post("/index/:id", function (req, res) { testdata.findbyid(req.params.id, function (err, theuser) { if (err) { console.log(err); } else { theuser.likes += 1; theuser.save(); console.log(theuser.likes); res.send({likecount: theuser.likes}); //something this... } }); });
Comments
Post a Comment