May 23, 2022
White Arrow icon
Back to all Elements

CMS Autocomplete

A short JavaScript code for transferring a CMS list into an autocomplete on an input field.

We need 2 elements for this to work:

  1. Search bar (this needs to be an input field)
  2. List of items (could be a static list or a CMS dynamic list)

The first part of the code sets a few constants on the page:

  • The List wrapper
  • The list
  • The search bar

// Collection List Wrapper
 const listWrap = document.getElementById('listWrap');

 // Collection List
 const list = document.getElementById('autoCompleteList');

 // Search Input Field
 const searchBar = document.getElementById('searchBar');

Copy

Next we have a 'keyup' event listener. This part 'listens' to any key pressed inside the search bar and filters through the items lists. It changes the css of each item (display:block or display:none) according to the term typed.

searchBar.addEventListener('keyup', function(e){
   const term = e.target.value.toLowerCase();
   // All the elements that will be searchable (can be the item, or a div inside each item)
   const searchItems = list.getElementsByClassName('list-item');
   Array.from(searchItems).forEach(function(item){
     const text = item.firstElementChild.textContent;
     if(text.toLowerCase().indexOf(term)!=-1){
       item.style.display = 'block';
     }
     else {
       item.style.display = 'none';
     }
   })
 })

Copy

The last part is the interaction that opens and closes the list when the focus is on the search bar.

Put all those 3 code snippets together at the custom code section of your page under the Before </body> tag.

// Open list when search bar is focused
 searchBar.addEventListener('focusin', (event) => {
   listWrap.style.maxHeight = "400px";
 });
 
 // Close list when search bar is focused
 searchBar.addEventListener('focusout', (event) => {
   listWrap.style.maxHeight = "0";
 });

Copy

Preview:

browser mockup
Share:
Heart icon

When your bath soap bar gets too small to use, don't throw it away! open the next bar, and when you finish showering, stick the small old bar to the back of the new bar. Onces they both dry, they will become one.

Might also interest you:

Scaleable Vanilla JS Nested Tabs

JavaScript
Cloneable
Code

Nested tabs in an accordion template

Read more
Blue arrow iconWhite Arrow icon

Buttons Hover Interactions

Cloneable
Interactions

A small collection of buttons and hover interactions.

Read more
Blue arrow iconWhite Arrow icon

3d Video Slider (swiper.js)

Cloneable
CMS
JavaScript

A 3d slider with video items, plays and pauses on click & slide change.

Read more
Blue arrow iconWhite Arrow icon