Implementing voting logic based on previous score
<p>Wondering how to handle this. I've done it previously, but it involves a lot of if/else statements and I can't seem to figure it out without resorting to that. I posted it on codereview and got someone to help me re-facor it, but now I'm trying to get this functionality working properly.</p>

<p>How this works now is, if you click "up", it'll increase the score 1 point. If you click "up" again, it'll decrease the score. That's fine. If you click "down" it'll have the same behavior. It will not however go below 0 ever, since I don't want to display a negative score.</p>

<p>Right now I'm just checking to see if the previous or next buttons have <code>.upColor</code> and <code>.downColor</code> css classes on them, which check if they've already voted. I'm having trouble trying to update the proper score based off of this especially if the original score is 0, or if the score is 10.</p>

<p>Logic I'm trying to implement:</p>

<p>E.g. Original score is 0:</p>

<ul>
<li>User votes up. Score goes to 1. User votes down. Score goes to 0 (not -1)</li>
<li>User votes down. Score stays at 0. User votes up. Score goes to 1.</li>
</ul>

<p>E.g. Original score is 10:</p>

<ul>
<li>User votes up. Score goes to 11. User votes down. Score goes to 9.</li>
<li>User votes down. Score goes to 9. User votes up. Score goes to 11.</li>
</ul>

<p>Code:</p>

<pre><code>$(function() {

var handleClick = function($btn) {
    var $voteContainer = $btn.parent();
    var scoreNode = $('.count');
    var originalScore = Number($voteContainer.data('original-score'));

    if ($btn.hasClass('down')) {
        if ($btn.prevAll('.up').hasClass('upColor')) {
            $btn.prevAll('.up').toggleClass('upColor');
            alert('voted up now voting down, decrease 2 points, but don\'t go below 0.');
        }
    }


    if ($btn.hasClass('up')) {
        if ($btn.nextAll('.down').hasClass('downColor')) {
            $btn.nextAll('.down').toggleClass('downColor');
            alert('voted down now voting up, increase by 2 points');
        }
    }

    var increment = $btn.hasClass('up') ? 1 : $btn.hasClass('down') &amp;&amp; originalScore &gt; 0 ? -1 : 0; // default

    // Only do something if there is an increment
    if (increment) {
        var currentScore = Number(scoreNode.text()) || 0;
        var newScore = currentScore + increment;
        var diff = Math.abs(originalScore - newScore);

        // Can't go more than + or - 1
        if (diff &gt; 1) {
            newScore = originalScore;
        }

        // Set new displayed value
        scoreNode.text(newScore);
    }
    $btn.hasClass('up') ? $btn.toggleClass('upColor') : $btn.toggleClass('downColor');
};

var upBtn = $('.up');
var downBtn = $('.down');

upBtn.add(downBtn).click(function() {
    var $btn = $(this);

    handleClick($btn);
});

});
</code></pre>

<p>Demo: <a href="http://jsfiddle.net/3kCPw/" rel="nofollow">http://jsfiddle.net/3kCPw/</a></p>
