JSFiddle - React, Tailwind, and code Playground

by someprimetime

HTML

<div class="vote-container" data-was="0">
  <button class="vote up">Up</button>
  <span class="count">0</span>
  <button class="vote down">Down</button>
</div>
<div class="vote-container" data-was="1">
  <button class="vote up">Up</button>
  <span class="count">1</span>
  <button class="vote down">Down</button>
</div>
<div class="vote-container" data-was="29">
  <button class="vote up active">Up</button>
  <span class="count">30</span>
  <button class="vote down">Down</button>
</div>
<div class="vote-container" data-was="20">
  <button class="vote up">Up</button>
  <span class="count">19</span>
  <button class="vote down active">Down</button>
</div>
<div class="vote-container" data-was="11">
  <button class="vote up">Up</button>
  <span class="count">11</span>
  <button class="vote down">Down</button>
</div>

CSS

button {
    cursor: pointer;
    border: none;
    padding:5px;
}

.up.active {
    background: blue;
    color: white;
}

.down.active {
    background: red;
    color: white;
}
.vote-container {
    width: 20px;
    margin:10px auto;
    text-align:center;
}

JavaScript

$(function() {

    $('button').click(function(e) {

        e.preventDefault();

        var $this = $(this);
        var $container = $(this).parent();
        var $buttons = $container.children('button');
        var $count = $container.children('.count');
        var votes = parseInt($count.text());
        var was = $container.data('was');
        var vote = ($this.hasClass('up')) ? 1 : -1;

        if ($this.hasClass('active')) {
            $this.toggleClass('active');
            $count.text(was);
        } else {
            if ($buttons.filter('.active').length) {
                $buttons.toggleClass('active');
                if (was + vote < 0) {
                    $count.text(votes + vote);
                    return false;
                }
            } else {
                if (was + vote < 0) {
                    $this.toggleClass('active');
                    return false;
                }
                $this.toggleClass('active');
            }
            $count.text(was + vote);
        }

    });

});