Skip to content

Instantly share code, notes, and snippets.

@jacobh
Created October 30, 2012 06:01
Show Gist options
  • Save jacobh/3978561 to your computer and use it in GitHub Desktop.
Save jacobh/3978561 to your computer and use it in GitHub Desktop.
$.fn.toggle_input = (options) ->
# used for our 3-way toggles such as sentiment and disclosure
defaults =
input: 'input'
toggles: '.toggle'
active_class: 'active'
can_deselect: true
get_value: ->
@text().trim().toLowerCase().replace ' ', ''
initialize: ->
input_val = @find(settings.input).attr 'value'
if input_val
toggle = @find(settings.toggles).filter(->
toggle_value = $.proxy(settings.get_value, $(this))()
toggle_value is input_val
)
toggle.click()
settings = $.extend defaults, options
@each ->
$this = $ this
$input = $this.find settings.input
$toggles = $this.find settings.toggles
$toggles.click ->
$this = $ this
if settings.can_deselect and $this.hasClass settings.active_class
# we want to deselect the clicked option
$input.val null
$this.removeClass settings.active_class
else
# get the new value out of the toggle and set the input to it
value = $.proxy(settings.get_value, $this)()
$input.val value
# update the classes on the toggles for UI
$toggles.removeClass settings.active_class
$this.addClass settings.active_class
false
$.proxy(settings.initialize, $this)()
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment