Skip to content

Instantly share code, notes, and snippets.

@VicVicos
Last active September 8, 2018 17:26
Show Gist options
  • Select an option

  • Save VicVicos/3187f1f073939462c3d6adb46f1fcf8d to your computer and use it in GitHub Desktop.

Select an option

Save VicVicos/3187f1f073939462c3d6adb46f1fcf8d to your computer and use it in GitHub Desktop.
Counter
<div class="counter">
<p class="number">
<span class="cminus position-count no-select">-</span>
<span class="value">1</span>
<span class="cplus position-count no-select">+</span>
</p>
<input type="number" min="1" value="1">
</div>
jQuery(function ($){
var counter = {
cInput: null,
setInput: function (elem) {
return this.cInput = elem;
},
getVal: function () {
return this.cInput.val();
},
setVal: function (value) {
return this.cInput.val(value);
},
cPlus: function () {
var currentVal = this.getVal();
return this.setVal(parseInt(currentVal) + 1);
},
cMinus: function () {
var currentVal = this.getVal();
if (currentVal <= 1) {
return this.setVal(1);
}
return this.setVal(parseInt(currentVal) - 1);
}
};
var counterElem = $('.counter');
counterElem.on('click', '.cplus', function(e) {
counter.setInput($(this).parents('.counter').find('input'));
counter.cPlus();
$(this).siblings('.value').html(counter.getVal());
$(counter.cInput).trigger('change');
});
counterElem.on('click', '.cminus', function(e) {
counter.setInput($(this).parents('.counter').find('input'));
counter.cMinus();
$(this).siblings('.value').html(counter.getVal());
$(counter.cInput).trigger('change');
});
}(jQuery));
.counter {
display: flex;
flex-wrap: nowrap;
justify-content: space-between;
}
.counter .number {
display: flex;
align-items: center;
width: 100%;
justify-content: space-between;
margin: 0;
}
.counter .value {
width: 40%;
height: 32px;
border: 1px solid #bebebe;
background-color: #fff;
border-radius: 2px;
display: inline-block;
text-align: center;
line-height: 28px;
font-size: 16px;
vertical-align: bottom;
}
.counter .position-count {
cursor: pointer;
display: inline-block;
border: 2px solid #ffcd00;
width: 32px;
height: 32px;
border-radius: 1px;
font-size: 16px;
line-height: 28px;
font-weight: 700;
text-align: center;
user-select: none;
}
.counter .position-count:hover {
background-color: #FFCD00;
}
.counter .cminus {
}
.counter .cplus {
}
.counter input[type="number"] {
display: none;
}
/* disable user selection of text */
.no-select {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment