Auto-Complete Textbox Highlighting in JavaScript


Auto-complete textbox highlighting in JavaScript refers to a feature that allows a user to quickly find and select a suggestion from a dropdown list while typing in a text input field. This feature is commonly used in search boxes, where the user types in a query, and suggestions based on their input appear in a dropdown menu.

The auto-complete feature in JavaScript works by using an event listener to capture the user's input, and then searching through a predefined list of options to find relevant matches. As the user types, the suggestions that match their input are displayed in a dropdown menu below the input field.

The highlighting feature comes into play when the user selects one of the suggestions from the dropdown menu. The selected suggestion is then displayed in the input field, with the matching part of the suggestion highlighted in some way, such as with bold text or a different color.

Implementing auto-complete textbox highlighting in JavaScript involves several steps, including creating the input field and dropdown menu, defining the list of options, capturing user input with an event listener, filtering the list of options based on the user's input, and displaying the filtered options in the dropdown menu. The highlighting feature is added by modifying the selected suggestion's appearance once it's selected by the user.

Overall, auto-complete textbox highlighting in JavaScript can improve user experience by making it faster and easier for users to find and select relevant information, whether they're searching for products, content, or other data.

Source Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Auto Complete Text Box</title>
    <link rel="stylesheet" href="css/style.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" />
  </head>
  <body>
    <nav>
      <div class="logo">Tutor Joe's</div>

      <div class="search-box">
        <div class="row">
          <input type="text" id="searchText" autocomplete="off" placeholder="Search Text Here.." />
          <button><i class="fa fa-search"></i></button>
        </div>
        <div class="suggest-box">
          <!-- <ul>
            <li>HTML Bootcamp</li>
            <li>CSS Complete Tutorial</li>
            <li>Full Stack</li>
          </ul> -->
        </div>
      </div>
    </nav>
    <script src="js/script.js"></script>
  </body>
</html>

js/script.js

const suggestBox = document.querySelector(".suggest-box");
const inputBox = document.querySelector("#searchText");

inputBox.addEventListener("keyup", filterSuggesstions);

inputBox.addEventListener("click", () => {
  inputBox.select();
});

async function filterSuggesstions() {
  const response = await fetch("./data/data.json");
  const KeywordsList = await response.json();
  let suggest = [];
  let input = this.value.trim();
  if (input.length) {
    suggest = KeywordsList.filter((keyword) => {
      return keyword.search.toLowerCase().includes(input.toLowerCase());
    });
  }
  display(suggest);

  if (!suggest.length) {
    suggestBox.innerHTML = "";
  }
}

function display(suggest) {
  const content = suggest.map((list) => {
    const data = list.search;
    return `<li onclick="selectInput('${data}')">${Highlight(data)}</li>`;
  });
  suggestBox.innerHTML = `<ul>${content.join("")}</ul>`;
}

function selectInput(data) {
  inputBox.value = data;
  suggestBox.innerHTML = "";
}

function Highlight(textToSearch) {
  const searchString = inputBox.value.toLowerCase();
  const startIndex = textToSearch.toLowerCase().indexOf(searchString);
  const highlightedText = textToSearch.substring(0, startIndex) + "<mark>" + searchString + "</mark>" + textToSearch.substring(startIndex + searchString.length);
  return highlightedText;
}

First, two variables suggestBox and inputBox are declared which represent the DOM elements of the dropdown suggestion box and the input textbox respectively.

An event listener is then added to the inputBox element which listens for a "keyup" event and triggers the filterSuggestions function.

Another event listener is added to the inputBox element which listens for a "click" event and selects the entire text in the input box when clicked.

The filterSuggestions function uses an async/await pattern to fetch a JSON data file containing a list of keywords. It then filters the list of keywords based on the user's input and displays the filtered list in the dropdown suggestion box by calling the display function. If there are no suggestions, the suggestBox element is emptied.

The display function takes the filtered suggestion list as input and uses the map method to create a new array of HTML li elements for each suggestion, with the Highlight function applied to each suggestion's search text. The resulting HTML code is then added to the suggestBox element.

The Highlight function takes the search text as input and returns the same text with the search term highlighted with HTML tags (<mark>). It does this by finding the index of the search term in the text, and then returning a modified version of the text string with the search term wrapped in the <mark> tags.

Finally, the selectInput function is called when a suggestion is clicked, which sets the value of the inputBox element to the selected suggestion and clears the suggestBox element.

data/data.json

[
  {
    "search": "How to learn web development"
  },
  {
    "search": "JavaScript frameworks"
  },
  {
    "search": "CSS tips and tricks"
  },
  {
    "search": "Front-end vs. Back-end development"
  },
  {
    "search": "Responsive web design"
  },
  {
    "search": "How to use Git for web development"
  },
  {
    "search": "Web development bootcamps"
  },
  {
    "search": "Web accessibility guidelines"
  },
  {
    "search": "Progressive Web Apps"
  },
  {
    "search": "UI/UX design for the web"
  },
  {
    "search": "React.js tutorial"
  },
  {
    "search": "Node.js frameworks"
  },
  {
    "search": "PHP best practices"
  },
  {
    "search": "SEO for websites"
  },
  {
    "search": "Web performance optimization"
  },
  {
    "search": "GraphQL API design"
  },
  {
    "search": "WordPress theme development"
  },
  {
    "search": "Web security best practices"
  },
  {
    "search": "jQuery plugins"
  },
  {
    "search": "CSS grid layouts"
  },
  {
    "search": "Web animations with CSS and JavaScript"
  },
  {
    "search": "Web scraping with Python"
  },
  {
    "search": "WebRTC video chat implementation"
  },
  {
    "search": "Responsive images"
  },
  {
    "search": "Debugging web applications"
  },
  {
    "search": "Web development trends in 2023"
  },
  {
    "search": "Bootstrap responsive design"
  },
  {
    "search": "Python web development frameworks"
  },
  {
    "search": "RESTful API design"
  },
  {
    "search": "Web accessibility testing"
  },
  {
    "search": "JavaScript design patterns"
  },
  {
    "search": "React Native app development"
  },
  {
    "search": "CSS preprocessors"
  },
  {
    "search": "Web performance metrics"
  },
  {
    "search": "Web development tools for Mac"
  },
  {
    "search": "WordPress plugin development"
  },
  {
    "search": "Web design trends in 2023"
  },
  {
    "search": "Database design for web applications"
  },
  {
    "search": "User authentication and authorization"
  },
  {
    "search": "JavaScript testing frameworks"
  },
  {
    "search": "Web hosting providers"
  },
  {
    "search": "Web development for mobile devices"
  },
  {
    "search": "React Native vs Flutter"
  },
  {
    "search": "Web scraping tools"
  },
  {
    "search": "Ruby on Rails tutorial"
  },
  {
    "search": "Web design principles"
  },
  {
    "search": "JavaScript data visualization"
  },
  {
    "search": "Vue.js components"
  },
  {
    "search": "Web typography best practices"
  },
  {
    "search": "Web application architecture"
  },
  {
    "search": "React Native app performance"
  },
  {
    "search": "CSS flexbox layouts"
  },
  {
    "search": "ASP.NET web development"
  },
  {
    "search": "Web accessibility audit"
  },
  {
    "search": "Web animations using SVG"
  },
  {
    "search": "Web development podcasts"
  },
  {
    "search": "Responsive web design frameworks"
  },
  {
    "search": "JavaScript unit testing"
  }
]

Finally, you can add some CSS styles to enhance the look and feel of the button and container. you can adjust the CSS styles as desired to match the design of your website.

css/style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  background-color: palegoldenrod;
  color: #333;
}

nav {
  width: 100%;
  min-height: 50px;
  background-color: #2f3640;
  color: #fff;
  padding: 10px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 25px;
  text-transform: uppercase;
  font-weight: 600;
  letter-spacing: 1px;
  color: palegoldenrod;
}

.search-box {
  width: 350px;
  background-color: #fff;
  border-radius: 2px;
  position: relative;
}

.search-box .row {
  display: flex;
  align-items: center;
  padding: 0px 5px;
}

input {
  flex: 1;
  height: 30px;
  border: none;
  outline: none;
  font-size: 14px;
  color: #333;
}

button {
  background: transparent;
  border: 0;
  outline: 0;
}
button .fa {
  font-size: 14px;
  color: #736f6f;
  cursor: pointer;
}
.suggest-box {
  position: absolute;
  width: 100%;
  max-height: 300px;
  background-color: #fff;
  overflow-y: scroll;
}

.suggest-box ul {
  border-top: 1px solid #999;
  padding: 15px 10px;
}

.suggest-box ul li {
  list-style: none;
  color: #333;
  border-radius: 3px;
  cursor: pointer;
  user-select: none;
  display: block;
  padding: 6px 2px;
}

.suggest-box ul li:hover {
  background-color: #e9f3ff;
}

::-webkit-scrollbar {
  width: 5px;
}
::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
::-webkit-scrollbar-thumb {
  background-color: #2f3640;
  border-radius: 8px;
}

@media (max-width: 600px) {
  nav {
    flex-direction: column;
  }
  .search-box {
    margin-top: 10px 0px;
  }
}

Output

Text Box Heightlighter

Overall, this code allows users to type in a search term and see a list of matching suggestions in a dropdown box with the matching part of the suggestion highlighted. When a suggestion is selected, the search term is filled into the input box, and the dropdown box is hidden.

Live Preview


List of Programs


JS Practical Questions & Answers


JS Practical Project