I have a list of resources which can be voted on. There are 3 voting states: upvoted, downvoted and no vote.
In a fashion identical to Stack Exchange voting, it follows these rules:
- If you upvote a post you've already upvoted, it will set it to 'no vote'
- If you upvote a post set to 'no vote' it will set it to upvote
- if you downvote a post you've upvoted, it will set it to 'downvote' (I bolded this because in another post everyone gave me grief that this way is 'stupid', yet every voting site I have seen uses this style... Reddit, Digg. Stack Overflow, etc)
The exact same rules (except inverse) hold true for downvote.
Here's how I call my sendVote()
function, when you click on upvote or downvote:
// Voting
$('.res-list').delegate('.vote .up', 'click', function() {
flashColor($(this),'#fffc00');
sendVote($(this).parent(),'upvoted');
return false;
});
$('.res-list').delegate('.vote .down', 'click', function() {
flashColor($(this),'#fffc00');
sendVote($(this).parent(),'downvoted');
return false;
});
I believe that above code is fine, but his code below is what I feel is awful and could really be refactored, but I don't know how. I'm kind of new to JavaScript and jQuery.
function sendVote(object, direction) {
var votesContainer = $(object).find('.m p');
var votes = parseInt($(votesContainer).html());
// UPVOTED
if (direction == 'upvoted') {
if ($(object).hasClass('downvoted')) {
// Overwrite Downvote
$(votesContainer).html(votes + 2);
$(object).removeClass('downvoted');
$(object).addClass(direction);
} else if ($(object).hasClass(direction)) {
// Undo Upvote
$(votesContainer).html(votes - 1);
$(object).removeClass(direction);
} else {
// Do Upvote
$(votesContainer).html(votes + 1);
$(object).addClass(direction);
};
// Ajax function here to /votes/upvote?id=x
// DOWNVOTED
} else {
if ($(object).hasClass('upvoted')) {
// Overwrite Upvote
$(votesContainer).html(votes - 2);
$(object).removeClass('upvoted');
$(object).addClass(direction);
} else if ($(object).hasClass(direction)) {
// Undo Downvote
$(votesContainer).html(votes + 1);
$(object).removeClass(direction);
} else {
// Do Downvote
$(votesContainer).html(votes - 1);
$(object).addClass(direction);
};
// Ajax function here to /votes/downvote?id=x
}
}