Created
March 12, 2013 20:05
-
-
Save carsontang/5146501 to your computer and use it in GitHub Desktop.
My implementation of autosuggest
This file contains hidden or 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 SuggestionController = { | |
_init: function() { | |
SuggestionController.queryInput = document.getElementById("query"); | |
SuggestionController.suggestionsOutput = document.getElementById("suggestions"); | |
SuggestionController.queryInput.addEventListener("keyup", SuggestionController.handleKeyup); | |
}, | |
generateSuggestions: function(list, input) { | |
if (input === "") | |
return []; | |
var suggestions = []; | |
for (var i = 0; i < list.length; i++) { | |
if (list[i].toLowerCase().indexOf(input.toLowerCase()) == 0) { | |
suggestions.push(list[i]); | |
} | |
} | |
return suggestions; | |
}, | |
populateSuggestions: function(suggestions) { | |
for (var i = 0; i < suggestions.length; i++) { | |
var suggestionNode = document.createElement("li"); | |
var suggestionNodeText = document.createTextNode(suggestions[i]); | |
suggestionNode.appendChild(suggestionNodeText); | |
SuggestionController.suggestionsOutput.appendChild(suggestionNode); | |
} | |
}, | |
handleKeyup: function(evt) { | |
if (SuggestionController._isValidKeyCode(evt.keyCode)) { | |
SuggestionController.removeSuggestions(); | |
var states = ["Arizona", "Official Hacker News T-Shirt", "Thai character", "O'Reilly Media", "Automatic: Your Smart Driving Assistant", "California", "New York", "North Carolina", "New Jersey", "Delaware", "North Dakota"] | |
var suggestions = SuggestionController.generateSuggestions(states, SuggestionController.queryInput.value); | |
SuggestionController.populateSuggestions(suggestions); | |
} | |
}, | |
removeSuggestions: function() { | |
var numSuggestions = SuggestionController.suggestionsOutput.childNodes.length; | |
for (var i = 0; i < numSuggestions; i++) { | |
SuggestionController.suggestionsOutput.removeChild(SuggestionController.suggestionsOutput.childNodes[0]); | |
} | |
}, | |
_isValidKeyCode: function(keyCode) { | |
if (keyCode < 8 || (keyCode > 8 && keyCode < 32) || (keyCode >= 33 && keyCode <= 46) || (keyCode >= 112 && keyCode <= 123)) { | |
return false; | |
} | |
return true; | |
} | |
}; | |
window.onload = SuggestionController._init; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment