Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions auto-complete.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ var autoComplete = (function(){
offsetTop: 1,
cache: 1,
menuClass: '',
selectorToInsert: 0,
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
Expand Down Expand Up @@ -82,7 +83,12 @@ var autoComplete = (function(){
}
}
addEvent(window, 'resize', that.updateSC);
document.body.appendChild(that.sc);

if (typeof o.selectorToInsert === "string" && document.querySelector(o.selectorToInsert) instanceof HTMLElement) {
document.querySelector(o.selectorToInsert).appendChild(that.sc);
} else {
document.body.appendChild(that.sc);
}

live('autocomplete-suggestion', 'mouseleave', function(e){
var sel = that.sc.querySelector('.autocomplete-suggestion.selected');
Expand Down Expand Up @@ -204,7 +210,16 @@ var autoComplete = (function(){
that.setAttribute('autocomplete', that.autocompleteAttr);
else
that.removeAttribute('autocomplete');
document.body.removeChild(that.sc);
try {
if (o.selectorToInsert && document.querySelector(o.selectorToInsert).contains(that.sc)) {
document.querySelector(o.selectorToInsert).removeChild(that.sc);
} else {
document.body.removeChild(that.sc);
}
} catch (error) {
console.log('Destroying error: can\'t find target selector', error);
throw error;
}
that = null;
}
};
Expand Down
39 changes: 39 additions & 0 deletions testcase.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./auto-complete.css">
</head>
<body>
<div class="ac" id="ac">
<input type="text">
</div>

<script src="./auto-complete.js"></script>

<script>



debugger;
var acBase = ['car', 'cat', 'camera'];

var ac = new autoComplete({
selector: '.ac input',
minChars: 2,
source: function(term, suggest){
term = term.toLowerCase();
var choices = acBase;
var matches = [];
for (i=0; i<choices.length; i++)
if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
suggest(matches);
},
selectorToInsert: '.ac'
});
</script>
</body>
</html>