Skip to content

Instantly share code, notes, and snippets.

@raducugheorghe
Last active August 29, 2015 14:14
Show Gist options
  • Save raducugheorghe/ac828b6168a03b6a8a14 to your computer and use it in GitHub Desktop.
Save raducugheorghe/ac828b6168a03b6a8a14 to your computer and use it in GitHub Desktop.
[Javascript] Autocomplete Textarea from localStorage
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