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

A tongue scraper is is so much better in cleaning your tongue instead of the normal brushing it.

Might also interest you:

Auto get Current Year

Cloneable
Code
JavaScript

Automatically insert the current year to any element with the class of 'year'

Read more
Blue arrow iconWhite Arrow icon

Scroll Menu to Current Link

Cloneable
CMS
Code

Using JS to scroll a div (menu) to the current link inside.

Read more
Blue arrow iconWhite Arrow icon

Background Video with Audio (using plyr.js)

Cloneable
Code
JavaScript

An embed video with Mute/UnMute button using plyr.js plugin.

Read more
Blue arrow iconWhite Arrow icon