Skip to content

Instantly share code, notes, and snippets.

@jspillers
Created October 13, 2011 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jspillers/1284380 to your computer and use it in GitHub Desktop.
Save jspillers/1284380 to your computer and use it in GitHub Desktop.
#var $context, $input, $shadow, current_tags, tag_name, template, view;
initialize: () ->
template = $('script.tag_mustache').html()
$context = $('span.tagging_container')
$hidden_input = $context.find('.tags_value')
if $context
$shadow = $context.find('.input_shadow')
$input = $context.find('.tag_input')
$context.find('.tag a.remove_tag').live 'click', ->
remove_tag $(this).closest('span.tag')
$context.live 'click', ->
$input.focus()
# needed in keypress for a held down key
$input.live 'keypress', (event) ->
auto_width $(this)
# ',' needed in keyup to remvoe trailing ,
$input.live 'keyup', (event) ->
if event.keyCode == 188
$(this).trigger('set_tag.key_up')
# delete or backspace needed in keydown to delete last char before last tag
$input.live 'keydown', (event) ->
if (event.keyCode == 8 || event.keyCode == 46) && $(this).val() == ''
remove_tag $context.find('.tag:last').remove()
$input.live 'set_tag', ->
add_tag $(this).val()
add_tag: (text) ->
tag_name = $.trim(text).replace(',','')
$tag = create_tag(tag_name)
$context.find('.tags').append($tag)
$input.val('')
update_hidden_input(tag_name, 'add')
auto_width: ($input) ->
$shadow.html $input.val().replace(/\s/g,' ')
$input.width $shadow.width() + 10
create_tag: (tag_name) ->
unless tag_name == ''
view = { tag_name: tag_name }
return $(Mustache.to_html(template, view))
remove_tag: ($tag) ->
$tag.remove()
$input.focus()
update_hidden_input $tag.attr('data-tag_name'), 'remove'
update_hidden_input: (tag_name, action) ->
current_tags = $hidden_input.val()
switch action
when 'add'
current_tags += ',' if current_tags != ''
$hidden_input.val(current_tags+tag_name)
when 'remove'
$hidden_input.val current_tags.replace(tag_name,'').replace(',,',',')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment