0

I cannot show voteUp/Down when I refresh page, because if I do voteUp/Down(+1 or -1) and refresh page, this return voteUp/Down (0) again. In this past I was using JSON, but the community recommended without JSON. So I have it, in this moment. Thanks.

    var voteUp = document.getElementById('vote-up');
var voteDown = document.getElementById('vote-down');

var handUp = once(function() {
    var total = Number(voteUp.innerHTML);
    total += 1;
    voteUp.innerHTML = total;
    saveVote();
});

voteUp.addEventListener('click', handUp);

var handDown = once(function() {
    var total = Number(voteDown.innerHTML);
    total -= 1;
    voteDown.innerHTML = total;
    saveVote();
});

voteDown.addEventListener('click', handDown);

function once(fn, context) {
    var result;

        return function() {
            if(fn) {
                result = fn.apply(context);
                fn = null;
            }
            return result;
        };
}

function saveVote() {
    var votes = voteUp, voteDown;
        localStorage.setItem('data', votes);
            console.log('saveVote');
}

function loadVote() {
    var votes = localStorage.getItem('data');
        if(!votes){
            return;
        }
            console.log(localStorage.getItem('data'));
}

loadVote();
supportsp
  • 63
  • 2
  • 11

2 Answers2

3
var voteUp = document.getElementById('vote-up');

function handUp() {
   var total = Number(voteUp.innerHTML);
   total += 1;
   voteUp.innerHTML = total;
}

voteUp.addEventListener('click',handUp,false);

It increments each one value by a click.

htoniv
  • 1,658
  • 21
  • 40
  • @UlisesContreras I'm glad you have a working code now but do you _understand_ why things weren't working before? – Jonast92 Dec 12 '14 at 19:01
  • @Jonast92 Yes, I needed a Number() to solution NaN. Now I'm watching to 'only +1', because I can to do infinitely click. – supportsp Dec 12 '14 at 19:41
  • Please refer this link this may help you [link]http://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh – htoniv Dec 14 '14 at 10:17
  • @htoniv You can help me in this stopPropagation() https://github.com/ulisescontreras/Transformed-Images-jQ – supportsp Dec 19 '14 at 16:37
  • @Jonast92 You know to use localStorage to loadVote when refresh page? – supportsp Dec 23 '14 at 08:52
1

There's no such thing as an =+ operator, there is an += operator, however.

+= Addition assignment.

Also, I'm pretty sure the typeof val is undefined since it's value is never defined in the argument passing of the method.

A variable which's type is undefined can certainly not contain a value which's a number (it's NaN) and thus the error message makes sense.

Jonast92
  • 4,964
  • 1
  • 18
  • 32