Last active
January 2, 2016 17:58
-
-
Save seanwash/8339895 to your computer and use it in GitHub Desktop.
Sliding Checkbox plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage | |
# $('element').sliderCheckbox() | |
# $('element').sliderCheckbox | |
# offLeft: int | |
$.fn.sliderCheckbox = (options) -> | |
settings = $.extend({ | |
offLeft: -64 | |
}, options) | |
return this.each -> | |
el = $(this) | |
if not el.hasClass('fancified') | |
inp = el.find 'input:checkbox' | |
slider = el.find '.slider' | |
inp.on 'focus', -> | |
el.addClass 'focused' | |
inp.on 'blur', -> | |
el.removeClass 'focused' | |
el.on 'click', (e) -> | |
inp.prop 'checked', !inp.prop('checked') | |
inp.trigger 'change' # triggers updateIndicator() | |
inp.focus() | |
updateIndicator() # this seems unnecessary - updateIndicator() has already been triggered by inp.change | |
updateIndicator = (noTransition = false) -> | |
checked = inp.prop 'checked' | |
inp.val(if checked then 'on' else 'off') | |
moveTo = if checked then 0 else settings.offLeft | |
setTimeout -> | |
slider.parent().toggleClass('checked', checked); | |
, 90 | |
# no why, but even if noTransition logs out as false, this evaluates as truthy | |
# unless explicit, which means sliderCheckboxes never animate. | |
# so, don't remove the `== true`, even though it's stupid | |
if noTransition == true | |
slider.css({ | |
'-webkit-transition': 'none', | |
'-moz-transition': 'none', | |
'-o-transition': 'none', | |
'transition': 'none' | |
}) | |
slider.css 'left', moveTo | |
else | |
slider.css({ | |
'-webkit-transition': 'left 180ms ease-out', | |
'-moz-transition': 'left 180ms ease-out', | |
'-o-transition': 'left 180ms ease-out', | |
'transition': 'left 180ms ease-out' | |
}) | |
slider.css 'left', moveTo | |
updateIndicator(true) | |
inp.on 'click', (e) -> | |
e.stopPropagation() | |
inp.on 'change', updateIndicator | |
el.addClass('fancified') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment