JSFiddle - React, Tailwind, and code Playground
HTML
<div id="count" class=""></div>
<a class="up" data-vote-direction="up">up</a>
<a class="down" data-vote-direction="down">down</a>
<br /><br />
Down: <span class="js-down-votes">0</span><br />
Up: <span class="js-up-votes">3</span>
JavaScript
$(function() {
var count = $('#count');
var up = $('.up');
var down = $('.down');
var downVotes = $('.js-down-votes');
var upVotes = $('.js-up-votes');
var totalUp = parseInt($('.js-up-votes').text(), 10);
var totalDown = parseInt($('.js-down-votes').text(), 10);
var currentCount = (totalUp - totalDown < 0) ? 0 : totalUp - totalDown;
count.text(currentCount);
up.add(down).click(function() {
var oldCount = parseInt(count.text(), 10);
var newCount;
var direction = $(this).data('vote-direction');
if (direction === 'up') {
if (!count.hasClass('upvoted')) { // first time voting (change later they could have voted down b4)
if (totalDown > totalUp) {
newCount = 0;
} else {
newCount = oldCount + 1;
}
count.addClass('upvoted');
upVotes.text(totalUp + 1);
} else {
if (totalUp - totalDown > 0) {
newCount = oldCount - 1;
} else {
newCount = 0;
}
count.removeClass('upvoted');
upVotes.text(totalUp);
}
} else if (direction === 'down') {
if (count.hasClass('upvoted')) {
// they voted up before
console.log('already voted up');
}
if (!count.hasClass('downvoted')) { // first time voting
if (totalDown > totalUp || totalDown === totalUp) {
newCount = 0;
} else {
newCount = oldCount - 1;
}
totalDown = totalDown + 1;
count.addClass('downvoted');
} else {
count.removeClass('downvoted');
totalDown = totalDown - 1;
}
...