Skip to content

Commit

Permalink
Merge pull request #60 from nicknickel/autocomplete-dropdown-opts
Browse files Browse the repository at this point in the history
enable autocomplete to accept dropdown options
  • Loading branch information
DanielRuf authored Jan 7, 2021
2 parents 31c6538 + 88fa44a commit 7da0213
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
6 changes: 6 additions & 0 deletions jade/page-contents/autocomplete_content.html
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ <h3 class="header">Options</h3>
<td></td>
<td>Sort function that defines the order of the list of autocomplete options.</td>
</tr>
<tr>
<td>dropdownOptions</td>
<td>Object</td>
<td>{}</td>
<td>Pass options object to select dropdown initialization.</td>
</tr>
</tbody>
</table>

Expand Down
30 changes: 23 additions & 7 deletions js/autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
data: {}, // Autocomplete data set
limit: Infinity, // Limit of results the autocomplete shows
onAutocomplete: null, // Callback for when autocompleted
dropdownOptions: {
// Default dropdown options
autoFocus: false,
closeOnClick: false,
coverTrigger: false
},
minLength: 1, // Min characters before autocomplete starts
sortFunction: function(a, b, inputString) {
// Sort function for sorting autocomplete results
Expand Down Expand Up @@ -152,14 +158,24 @@
this.$inputField.append(this.container);
this.el.setAttribute('data-target', this.container.id);

this.dropdown = M.Dropdown.init(this.el, {
autoFocus: false,
closeOnClick: false,
coverTrigger: false,
onItemClick: (itemEl) => {
this.selectOption($(itemEl));
// Initialize dropdown
let dropdownOptions = $.extend(
Autocomplete.defaults.dropdownOptions,
this.options.dropdownOptions
);
let userOnItemClick = dropdownOptions.onItemClick;

// Ensuring the selectOption call when user passes custom onItemClick function to dropdown
dropdownOptions.onItemClick = (el) => {
this.selectOption($(el));

// Handle user declared onItemClick if needed
if (userOnItemClick && typeof userOnItemClick === 'function') {
userOnItemClick.call(this.dropdown, this.el);
}
});
};

this.dropdown = M.Dropdown.init(this.el, dropdownOptions);

// Sketchy removal of dropdown click handler
this.el.removeEventListener('click', this.dropdown._handleClickBound);
Expand Down

0 comments on commit 7da0213

Please sign in to comment.