Last active
June 12, 2017 16:51
-
-
Save makotot/6445212 to your computer and use it in GitHub Desktop.
incremental search
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
| /** | |
| * Incremental Search | |
| */ | |
| var IncrementalSearch = function (targetInput, targetTable) { | |
| this.targetInput = targetInput; | |
| this.targetTable = targetTable; | |
| this.query = ''; | |
| this.dataList = []; | |
| this.filterList = []; | |
| }; | |
| IncrementalSearch.prototype = { | |
| init: function () { | |
| this.initDataList(); | |
| this.attachEvent(); | |
| }, | |
| attachEvent: function () { | |
| var self = this, | |
| eventHandler = function (e) { | |
| self.search(e); | |
| }; | |
| this.util.addEvent(this.targetInput, 'input', eventHandler); | |
| }, | |
| search: function () { | |
| this.query = (this.targetInput.value).toLowerCase(); | |
| if (this.query.length) { | |
| this.filterData(); | |
| } else { | |
| this.clearFilter(); | |
| } | |
| }, | |
| initDataList: function () { | |
| var i, max, | |
| targetTable = this.targetTable, | |
| tbody = targetTable.getElementsByTagName('tbody'), | |
| th = tbody[0].getElementsByTagName('th'); | |
| this.th = th; | |
| for (i = 0, max = th.length; i < max; i++) { | |
| this.dataList.push(th[i]); | |
| } | |
| }, | |
| filterData: function () { | |
| this.filterList = []; | |
| for (var i = 0, max = this.dataList.length; i < max ; i++) { | |
| this.filterList.push(this.filter(this.th[i])); | |
| } | |
| this.changeDisplay(); | |
| }, | |
| filter: function (data) { | |
| var textData = ('innerText' in document) ? data.innerText : data.textContent; | |
| textData = textData.toLowerCase(); | |
| return textData.indexOf(this.query) > -1; | |
| }, | |
| changeDisplay: function () { | |
| for (var i = 0, max = this.dataList.length; i < max; i ++) { | |
| this.th[i].parentNode.style.display = (this.filterList[i]) ? '' : 'none'; | |
| } | |
| }, | |
| clearFilter: function () { | |
| for (var i = 0, max = this.dataList.length; i < max; i++) { | |
| this.th[i].parentNode.style.display = ''; | |
| } | |
| } | |
| }; | |
| IncrementalSearch.prototype.util = { | |
| addEvent: function (elem, ev, fn) { | |
| if (elem.addEventListener) { | |
| elem.addEventListener(ev, fn, false); | |
| } else if (elem.attachEvent) { | |
| elem.attachEvent('on' + ev, fn); | |
| } else { | |
| elem['on' + ev] = fn; | |
| } | |
| } | |
| }; | |
| var increSearch = new IncrementalSearch(document.getElementById('incremental-search-field'), document.getElementById('incremental-search-table')); | |
| increSearch.init(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment