KC Here KC Here - 5 months ago 18
Javascript Question

How to make my upvote/downvote button store cookies and count votes only 1 time

Take a look at this https://fiddle.jshell.net/tnvv0dds/4/ I made this upvote/downvote button for my website, but it resets every time I refresh the website + it counts votes every time I click on it. I have no idea how to fix it since I am a bit new. Can someone make a javascript suggestion for me or give me a website link where I can learn it? I spent 3-4 days in searching it without success.

Answer

You can learn HTML5 Web Storage, and use them with the following code.

$(document).ready(function() {
    if(localStorage.getItem("count") == null)
        $("#count").text(0);
    else
        $("#count").text(localStorage.getItem("count"));
});

var counter = 0;
$("#plus").click(function(){
  counter++;
  $("#count").text(counter);
  localStorage.setItem("count", counter);
});

$("#minus").click(function(){
  counter--;    
  $("#count").text(counter);
  localStorage.setItem("count", counter);
});
Comments