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:

Share:

Destin's Youtube channel Smarter Every Day is one of my favourite places on the web.

Might also interest you:

3d Video Slider (swiper.js)

Cloneable
CMS
JavaScript

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

Read more
White Arrow icon

Glossary

Cloneable
JavaScript
CMS

A clonable for creating an Alphabetical glossary

Read more
White Arrow icon

Dynamic Height

Code
Tricks
JavaScript

A (custom code) solution that combines CSS variables and Vanilla JavaScript for the shrinking / growing of browser top & bottom bars.

Read more
White Arrow icon