Last active
August 29, 2015 14:14
-
-
Save raducugheorghe/ac828b6168a03b6a8a14 to your computer and use it in GitHub Desktop.
[Javascript] Autocomplete Textarea from localStorage
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
var AutocompleteTextarea = function () { | |
this.lastFocus = {}; | |
}; | |
AutocompleteTextarea.prototype = (function () { | |
function setSave(textareaId, storageKey) { | |
$("form").on("submit", function (ev) { | |
var value = $("#" + textareaId).val(); | |
if (!storageKey) return; | |
if (!value) return; | |
var storageData = null; | |
if (window.localStorage[storageKey]) { | |
try { | |
storageData = JSON.parse(window.localStorage[storageKey]); | |
} catch (e) { | |
window.localStorage.removeItem(storageKey); | |
} | |
} | |
if (!storageData) storageData = []; | |
var newStorage = [value], | |
currentValue, | |
i = 0; | |
while (newStorage.length <= 5 && (currentValue = storageData[i++])) { | |
if (currentValue != value) { | |
newStorage.push(currentValue); | |
} | |
} | |
window.localStorage[storageKey] = JSON.stringify(newStorage); | |
}); | |
} | |
var initAutocomplete = function (textareaId) { | |
var that = this; | |
if (!textareaId) return; | |
if (!window.localStorage) return; | |
var storageKey = "autocompleteTextarea" + textareaId; | |
setSave(textareaId, storageKey); | |
if (!window.localStorage[storageKey]) return; | |
var storageData = null; | |
try { | |
storageData = JSON.parse(window.localStorage[storageKey]); | |
} catch (e) { | |
window.localStorage.removeItem(storageKey); | |
} | |
if (storageData == null) return; | |
$("#" + textareaId) | |
.autocomplete({ | |
source: storageData, | |
minLength: 0, | |
autoFocus: true | |
}) | |
.on("keydown", function (ev) { | |
var $this = $(this); | |
var val = $this.val(); | |
if (val == "" && ev.keyCode == 40) { | |
$this.autocomplete('search', val); | |
} | |
}) | |
.on("focus", function () { | |
that.lastFocus[this.id] = 1; | |
}) | |
.on("blur", function () { | |
that.lastFocus[this.id] = -1; | |
}) | |
.on("click", function (ev) { | |
var $this = $(this); | |
var val = $this.val(); | |
if (that.lastFocus[this.id] % 2 == 0) { | |
$this.autocomplete('search', val); | |
} else { | |
$this.autocomplete('close'); | |
} | |
that.lastFocus[this.id]++; | |
}); | |
}; | |
return { initFor: initAutocomplete }; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment