Skip to content

Instantly share code, notes, and snippets.

@yaapis
Created March 2, 2016 10:57
Show Gist options
  • Save yaapis/6de2cdbc6b04402af4c2 to your computer and use it in GitHub Desktop.
Save yaapis/6de2cdbc6b04402af4c2 to your computer and use it in GitHub Desktop.
((jQuery) ->
jQuery.fn.extend incrementButtons: (options) ->
defaults =
minVal: null
maxVal: null
step: 1
incClass: "inc"
decClass: "dec"
callback: (value) ->
getNumVal = (element) -> #get numeric value of an object
value = Number(element.val())
(if isNaN(value) then 0 else value)
correctValue = (min, max, value) ->
checkMin = min? and not isNaN(0 + min)
checkMax = max? and not isNaN(0 + max)
return max if value > max and checkMax
return min if value < min and checkMin
value
options = jQuery.extend(defaults, options)
@each ->
obj = jQuery(this)
# Wrap obj:
obj.wrap "<div class=\"increment\"></div>"
# Create buttons:
decButton = obj.after("<a href=\"#\" class=\"" + options.decClass + "\">-</a>").next()
incButton = obj.after("<a href=\"#\" class=\"" + options.incClass + "\">+</a>").next()
# Focus value:
focusValue = undefined
incButton.click (e) ->
e.preventDefault()
obj.val correctValue(options.minVal, options.maxVal, (getNumVal(obj) + options.step))
obj.trigger 'change'
options.callback getNumVal(obj)
decButton.click (e) ->
e.preventDefault()
obj.val correctValue(options.minVal, options.maxVal, (getNumVal(obj) - options.step))
obj.trigger 'change'
options.callback getNumVal(obj)
obj.focus ->
focusValue = obj.val()
obj.blur ->
obj.val correctValue(options.minVal, options.maxVal, getNumVal(obj))
obj.trigger 'change'
options.callback getNumVal(obj) unless obj.val() is focusValue
) jQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment