Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <section class="container">
    <h1>Autocomplete input field</h1>
    <p>A simple autocomplete / suggested search script.</p>
    
    <hr>
    
    <div class="autocomplete">
        <input type="text" class="autocomplete-input">
        <ul class="autocomplete-list"></ul>
    </div>
    
    <p class="hint">Hint: Try typing "John" into the input</p>
</section>
              
            
!

CSS

              
                @import url(https://fonts.googleapis.com/css?family=Roboto);

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f0f0f5;
    font-family: 'Roboto';
    color: #999;
    font-size: 18px;
}

h1 {
    color: #333;
    margin-bottom: 10px;
}

hr {
    width: 48px;
    border: none;
    background-color: #bbb;
    height: 1px;
    margin-top: 32px;
    margin-bottom: 30px;
}

.hint {
    font-style: italic;
    font-size: 15px;
    padding-top: 16px;
    color: #999;
}

.container {
    max-width: 50em;
    margin: 0 auto;
    
    height: 100vh;
    
    display: flex;
    
    justify-content: center;
    align-items: center;
    
    flex-flow: column;
}

.autocomplete {
    position: relative;
}

.autocomplete-input {
    font-family: 'Roboto';
    padding: 1em;
    border: 1px solid transparent;
    box-shadow: 0 0 0 #ddd;
    
    transition: all 0.35s ease-out;
    color: #999;
    font-size: 18px;
    
    width: 20em;
    
    &:focus {
        border-color: #ddd;
        outline: none;
        box-shadow: 0 0 10px #ddd;
    }
}

.cf{
    &:after{
        content:"";
        display:table;
        clear:both;
    }
}

.autocomplete-list {
    position: absolute;
    list-style-type: none;
    background: #fff;
    width: 100%;
    margin-top: 4px;
    box-shadow: 0 0 10px #ddd;
    border-top: 1px solid #ddd;
    
    transition: all 300ms ease-out;
    transform: scale(1) translateY(0);
    transform-origin: center center;
    
    &.hide-list {
        opacity: 0;
        transform: scale(0.875) translateY(-12px);
    }
    
    .list-item {
        .name,
        .title {
            display: block;
        }
        
        .name {
            color: #f06;
            padding-bottom: 5px;
        }
        
        .title {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }
        
        img {
            height: 48px;
            vertical-align: top;
            float: left;
            
            padding-right: 10px;
        }
        
        a {
            display: block;
            padding: 1em;
            color: #999;
            text-decoration: none;
            
            transition: all 100ms ease;
        }
        
        &:hover,
        &.highlight {
            a {
                background: #dddde4;
                color: #333;
            }
        }
    }
}
              
            
!

JS

              
                function getKeyByValue(obj, value) {
    return Object.keys(obj).find(key => obj[key] === value);
}

function objectByString(obj, str) {
	return str.split('.').reduce(function(prev, curr) {
	        return prev ? prev[curr] : undefined
	    }, obj || self)
}

const autocomplete = (function() {
    let keyCodes = {
        'ARROW_DOWN': 40,
        'ARROW_UP': 38,
        'TAB': 9,
        'ENTER': 13,
        'ESC': 27
    };
    
    const updateResults = (settings) => {
        let { userValue, data, filterBy } = settings;
        
        let searchTextClean = userValue.toLowerCase();
        let searchWords = searchTextClean.split(' ');
        
        let filteredItems = data.filter((item) => {
            let itemString = item;
            
            if (typeof itemString == 'object') {
                itemString = objectByString(item, filterBy);
            }
            
            let itemValue = itemString.toLowerCase();

            return searchWords.every((word) => itemValue.includes(word));
        });
        
        const results = filteredItems.map(item => settings.item(item));
        let resultsContainer = settings.resultsContainer;
        
        resultsContainer.innerHTML = '';
        
        if (!results.length) {
            return resultsContainer.classList.add('hide-list');
        }
        
        resultsContainer.classList.remove('hide-list');
        
        results.forEach(item => resultsContainer.innerHTML += item);
        
        return resultsContainer;
    }
    
    const incrementHighlightedItem = (action, resultItems, activeItem, activeIndex) => {
        if (
            (resultItems.length == (activeIndex + 1) && action == 'ARROW_DOWN') ||
            (activeIndex == 0 && action == 'ARROW_UP')
           ) {
            return true;
        }
        
        let newIndex = action == 'ARROW_UP' ? activeIndex - 1 : activeIndex + 1;
        
        activeItem.classList.remove('highlight');
        
        return resultItems[newIndex].classList.add('highlight');
    };
    
    const handleInputEvents = (e, settings) => {
        if (e.target.value.length < 3) {
            return settings.resultsContainer.classList.add('hide-list');
        }
        
        let action = getKeyByValue(keyCodes, e.keyCode);
        
        settings.resultsContainer.classList.remove('hide-list');
        settings.userValue = e.target.value;
        
        let resultItems = Array.from(settings.resultsContainer.children);
        let activeItem = false;
        
        if (resultItems.length) {
            activeItem = resultItems.filter(item => item.classList.contains('highlight'))[0];
        }
        
        switch (action) {
            case 'TAB':
            case 'ARROW_UP':
            case 'ARROW_DOWN':
                if (!activeItem) {
                    return resultItems[0].classList.add('highlight');
                }
                
                let activeIndex = resultItems.indexOf(activeItem);

                return incrementHighlightedItem(action, resultItems, activeItem, activeIndex);

                break;
                
            case 'ESC':
                settings.resultsContainer.innerHTML = '';
                settings.resultsContainer.classList.add('hide-list');
                
                return false;
                
                break;
                
            case 'ENTER':
                if (!activeItem) {
                    activeItem = resultItems[0];    
                }
                
                let anchor = activeItem.tagName == 'a' ? activeItem : activeItem.querySelector('a');
                
                return anchor.click();
                
                break;
                
            default:
                return updateResults(settings);
        }   
    }
    
    const render = (item, settings) => {
        const input = item.querySelector('.autocomplete-input');
        const list = item.querySelector('.autocomplete-list');
        
        settings.resultsContainer = list;
        settings.resultsContainer.classList.add('hide-list');
        
        input.addEventListener('keyup', (e) => (
            handleInputEvents(e, settings)
        ));
        
        input.addEventListener('focusin', (e) => ( 
            handleInputEvents(e, settings) 
        ));
        
        input.addEventListener('focusout', (e) => (
            settings.resultsContainer.classList.add('hide-list')
        ));
    };
    
    return (args = {}) => {
        let settings = Object.assign({}, {
            'element': [],
            'data': {},
            'filterBy': 'title',
            'item': function(title = {}) {
                return (
                    '<li class="list-item">' + 
                        '<a href="http://google.com">' + title + '</a>' +
                    '</li>'
                );
            }
        }, args);
        
        return settings.element.forEach((item) => render(item, settings));
    };
}());

let sampleData = [
  {
    name: 'John Smith',
    title: 'Explorer',
    image: 'https://www.nps.gov/jame/learn/historyculture/images/jsmith-apva.jpg'
  },
  {
    name: 'John Bradford',
    title: 'Prebendary',
    image: 'https://upload.wikimedia.org/wikipedia/en/a/aa/John_Bradford.jpg'
  },
  {
    name: 'John Bonham',
    title: 'Drummer',
    image: 'https://www.thefamouspeople.com/profiles/images/john-bonham-3.jpg'
  },
];

let simpleSampleData = ['john d smith', 'jane a doe', 'john jacob jingleheimer', 'apple', 'pie'];

let test = autocomplete({
    element: document.querySelectorAll('.autocomplete'),
    data: sampleData,
    filterBy: 'name',
    item: function(item) {
        return (
            '<li class="list-item">' + 
                '<a href="http://google.com" class="cf">' + 
                    '<img src="' + item.image + '" />' +
                    '<span class="name">' + item.name + '</span>' +
                    '<span class="title">' + item.title + '</span>' +
                '</a>' +
            '</li>'
        );
    }
});
              
            
!
999px

Console