JSFiddle - React, Tailwind, and code Playground
by someprimetime
HTML
<div class="vote-container" data-original-score="0">
<button class="up_arrow">Up</button>
<span class="count">0</span>
<button class="down_arrow">Down</button>
</div>
<div class="vote-container" data-original-score="1">
<button class="up_arrow">Up</button>
<span class="count">1</span>
<button class="down_arrow">Down</button>
</div>
<div class="vote-container" data-original-score="29">
<button class="up_arrow active">Up</button>
<span class="count">29</span>
<button class="down_arrow">Down</button>
</div>
<div class="vote-container" data-original-score="20">
<button class="up_arrow">Up</button>
<span class="count">20</span>
<button class="down_arrow active">Down</button>
</div>
<div class="vote-container" data-original-score="11">
<button class="up_arrow">Up</button>
<span class="count">11</span>
<button class="down_arrow">Down</button>
</div>
CSS
button {
background: url(//b56a4b135274efeb1f5a-b4f1d8b499f2c23281383392e57b9506.r50.cf2.rackcdn.com/vote_arrow.png) no-repeat;
cursor: pointer;
display: block;
height: 13px;
margin-left: 3px;
overflow: hidden;
position: relative;
text-indent: -9999px;
margin: 0 auto;
width: 18px;
border: none;
}
.up_arrow {
background-position: -18px 0;
}
.down_arrow {
background-position: -18px -14px;
}
.up_arrow:hover,
.up_arrow.active {
background-position: 0 0;
}
.down_arrow:hover,
.down_arrow.active {
background-position: 0 -14px;
}
.vote-container {
width: 20px;
margin:10px auto;
text-align:center;
}
JavaScript
$(function() {
$('button').click(function(e) {
e.preventDefault();
var $this = $(this),
$container = $(this).closest('.vote-container'),
$buttons = $container.children('button'),
$count = $container.children('.count'),
votes = Number($count.text()),
originalScore = $container.data('original-score'),
delta = ($this.hasClass('up_arrow')) ? 1 : -1;
if ($this.hasClass('active')) {
$this.toggleClass('active');
$count.text(originalScore);
} else {
if ($buttons.filter('.active').length) {
$buttons.toggleClass('active');
if (originalScore + delta < 0) {
$count.text(votes + delta);
return false;
}
} else {
if (originalScore + delta < 0)
return false;
$this.toggleClass('active');
}
$count.text(originalScore + delta);
}
});
});