Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Searchable {
- constructor(items = [], options = {}){
- this.version = '0.0.1';
- this.controller = options.controller;
- this.input = options.input;
- this.output = options.output;
- this.outputList = this.controller.createElement("UL");
- this.items = items;
- this.minTermLength = options.minTermLength;
- this.events = {
- };
- this.outputList.classList.add('searchable-results');
- this.output.appendChild(this.outputList);
- this.input.addEventListener('keyup', this.search.bind(this));
- }
- search(){
- this.outputList.classList.remove('has-results');
- this.clearChildElements(this.outputList);
- if(this.input.value.length > this.minTermLength){
- let regexString = `^${this.input.value.replace(/(\w+)/g, "(?=.*$1)")}.*$`;
- let regex = new RegExp(regexString.replace(' ', ''), 'gi');
- let filteredItems = this.items.filter(function(item){
- return regex.test(item.tag);
- });
- if(filteredItems > 0){
- this.outputList.classList.add('has-results');
- }
- this.printResults(filteredItems);
- }
- return this;
- }
- clearChildElements(parentNode){
- while (parentNode.lastChild) {
- parentNode.removeChild(parentNode.lastChild);
- }
- return this;
- }
- printResults(filteredItems){
- filteredItems.forEach(function(item){
- let listItem = this.controller.createElement("LI");
- item.content.tagName ? listItem.appendChild(item.content) : listItem.innerHTML = item.content;
- this.outputList.appendChild(listItem);
- });
- return this;
- }
- add(tag = 'search', content = 'search'){
- this.items.push({
- tag,
- content
- });
- return this;
- }
- clear(){
- this.input.value = '';
- this.outputList.remove('has-results');
- this.clearChildElements(this.outputList);
- }
- }
- window.srchble = new Searchable();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement