Created
November 2, 2015 20:42
-
-
Save erisfully/243d1c37058946590738 to your computer and use it in GitHub Desktop.
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
turnHashtagsToTags: function () { | |
var $this = $(this); | |
var inputting; | |
var inputPosition; | |
var charsEntered; | |
var actualValue; | |
function commit(){ | |
var $tagsInput = $('.bootstrap-tagsinput input'); | |
if (inputting) { | |
inputting = false; | |
if (charsEntered){ | |
// Press ENTER on the tags field | |
$tagsInput.trigger(jQuery.Event('keypress', { which: 13 })); | |
} | |
} | |
} | |
function start(){ | |
inputting = true; | |
actualValue = ''; | |
charsEntered = 0; | |
inputPosition = 0; | |
} | |
function charIsValid(char){ | |
return char.match(/[a-z0-9_-]/i) && !(char.match(/\d/) && !charsEntered) | |
} | |
function setValue(val){ | |
var $tagsInput = $('.bootstrap-tagsinput input'); | |
actualValue = val; | |
var validVal = _.select(val, function(c){ return charIsValid(c) }).join(''); | |
$tagsInput.val(validVal.toLowerCase()); | |
} | |
function add(code){ | |
var char = String.fromCharCode(code); | |
if (inputting) { | |
inputPosition++; | |
charsEntered++; | |
var initialVal = actualValue; | |
var beforeInputPosition = initialVal.slice(0, inputPosition - 1); | |
var afterInputPosition = initialVal.slice(inputPosition - 1, initialVal.length); | |
var newVal = beforeInputPosition + char + afterInputPosition; | |
setValue(newVal); | |
} | |
} | |
function subtract(){ | |
if (inputting) { | |
inputPosition--; | |
charsEntered--; | |
var initialVal = actualValue; | |
var newVal = initialVal.substring(0, initialVal.length - 1); | |
setValue(newVal); | |
if (charsEntered < 0){ commit() } | |
} | |
} | |
$this.on('click', function(){ | |
commit(); | |
}); | |
$this.on('keyup', function(){ | |
var code = event.which; | |
switch (code) { | |
case 8: // BACKSPACE | |
subtract(); | |
break; | |
case 38: // UP ARROW | |
commit(); | |
case 39: // RIGHT ARROW | |
inputPosition++; | |
if (inputPosition > charsEntered){ commit() } | |
break; | |
case 40: // DOWN ARROW | |
commit(); | |
break; | |
case 32: // 'SPACE' | |
commit(); | |
break; | |
case 13: // 'ENTER' | |
commit(); | |
break; | |
case 37: // LEFT ARROW | |
inputPosition--; | |
if (inputPosition < 0){ commit() } | |
break; | |
} | |
}); | |
$this.on('keypress', function(){ | |
var code = event.which; | |
switch (code) { | |
case 35: // # | |
commit(); | |
start(); | |
break; | |
default: // Anything else | |
add(code); | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment