top of page

Dynamic Searchable Dropdown of Trendy Hashtags

Dynamic Searchable Dropdown Blog Image



Hey y'all! Today I decided to give a tutorial about how to create a searchable drop down list that dynamically jumps to text in the list as the user types. I was asked how to do something similar to this by a junior developer, and I figured that this might be a good topic to provide for anyone of you that might want to know too.


To make this interesting, I decided to use trending hashtags as the values for the dropdown list, but you can replace the values in your dropdown file with whatever you need to get your task done. In this blog post, I show you the json file, the html and javascript code to get the dynamically searchable dropdown list working, and the commands to run the code.


The Trendy Hashtags JSON File

First, let's get acquainted with our key player: the `trendyHashtags.json` file. This file houses a carefully curated list of hashtags that encapsulate the spirit of coding. Actually, this is just a list of hashtags that I have used at some point over the last few years that I could remember for the purposes of this tutorial. Be sure to replace the values in this file with whatever values that are necessary for your search bar.

[
  "AlgorithmAdventures",
  "BinaryBard",
  "BitByBit",
  "ByteBack",
  "ByteMe",
  "CodeArt",
  "CodeCrush",
  "CodeCreators",
  "CodeDreams",
  "CodeEveryday",
  "CodeGoals",
  "CodeHarmony",
  "CodeLife",
  "CodeNinja",
  "CodeSculptor",
  "CodeTalk",
  "CodeWonders",
  "CodersGonnaCode",
  "CodingJourney",
  "CyberPunk",
  "DataDriven",
  "DebugDynasty",
  "DevCommunity",
  "DigitalDance",
  "DigitalFuture",
  "FutureCoder",
  "FutureOfTech",
  "GeekChic",
  "HackathonHero",
  "HackThePlanet",
  "HelloWorld",
  "InfiniteLoop",
  "InnovationStation",
  "JavaScriptMagic",
  "NerdAlert",
  "PixelPerfection",
  "PixelPioneer",
  "QuantumCoding",
  "SyntaxSorcerer",
  "TechInnovation",
  "TechTalk",
  "TechTonic",
  "TechTribe",
  "TechTrends",
  "WebDesign",
  "WebDev"
]

Understanding `index.html`: The Canvas of Magic

Now, let's explore the heart of our project - the `index.html` file. This HTML file is where the magic happens. It orchestrates the dynamic dropdown experience with JavaScript. I will break this down into sections for us to get a better idea of the important parts.


1. HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Searchable Dropdown</title>
</head>

<body>
  <!-- The container to hold our dynamic dropdown -->
  <div id="container"></div>

  <!-- JavaScript code for the dynamic dropdown -->
  <script>
    // JavaScript code that we discuss below goes here
  </script>
</body>
</html>

This is the basic structure of our HTML file. The `<div>` with the id "container" will hold our dynamic dropdown, and the `<script>` tag contains the JavaScript code responsible for its functionality.


2. JavaScript Magic

Now, let's delve into the JavaScript code that creates the dynamic dropdown.

<script>
  fetch('trendyHashtags.json')
    .then(response => response.json())
    .then(data => {
      // Sort the data alphabetically
      var values = data.sort();

      var select = document.createElement("select");
      select.name = "trendyHashtags";
      select.id = "trendyHashtags";

      for (const val of values) {
        var option = document.createElement("option");
        option.value = val;
        option.text = val.charAt(0).toUpperCase() + val.slice(1);
        select.appendChild(option);
      }

      var label = document.createElement("label");
      label.innerHTML = "Choose a Hashtag: ";
      label.htmlFor = "trendyHashtags";

      var searchInput = document.createElement("input");
      searchInput.type = "text";
      searchInput.id = "searchInput";
      searchInput.placeholder = "Search hashtags";

      document.getElementById("container").appendChild(label);
      document.getElementById("container").appendChild(searchInput);
      document.getElementById("container").appendChild(select);

      document.getElementById("searchInput").addEventListener("input", function () {
        var searchText = this.value.toLowerCase();
        var filteredOptions = values.filter(function (val) {
          return val.toLowerCase().includes(searchText);
        });

        updateDropdownOptions(filteredOptions);
      });

      function updateDropdownOptions(options) {
        select.innerHTML = "";

        for (const val of options) {
          var option = document.createElement("option");
          option.value = val;
          option.text = val.charAt(0).toUpperCase() + val.slice(1);
          select.appendChild(option);
        }
      }

      document.getElementById("trendyHashtags").addEventListener("change", function () {
        var choice = this;
        var text = choice.options[choice.selectedIndex].text;
        console.log("You've chosen:", text);
      });
    })
    .catch(error => console.error('Error fetching JSON:', error));
</script>

This JavaScript code dynamically creates a dropdown with options from our JSON file, adds a label and a search input for enhanced user experience, and sets up event listeners for real-time updates.


Setting Up a Local Server

To run our project smoothly, we'll use a local server. Here's a step-by-step guide using Python's built-in http.server:


1. Install Python (if not already installed)

Visit https://www.python.org/ and follow the installation instructions for your operating system.


2. Open a Terminal or Command Prompt

- On Windows: Press Win + R, type cmd, and press Enter.

- On macOS: Press Cmd + Space, type Terminal, and press Enter.

- On Linux: Use your preferred terminal application.


3. Navigate to the Project Directory

Use the cd command to navigate to the directory containing your HTML and JSON files.

cd path/to/your/project

4. Start the Local Server

For Python 3:

python -m http.server

5. Access the Application

Open your web browser and go to http://localhost:8000. Click on your `index.html` file to launch the dynamic dropdown experience.


6. Stop the Local Server

When you're done testing, return to the terminal where the server is running and press Ctrl + C to stop the server.


Use Your Cool New Dynamic Searchable Dropdown

Now that your local server is up and running, explore the dropdown. The search bar dynamically filters the hashtags, providing a smooth and interactive selection process. Choose your favorite coding hashtag, and witness the magic unfold!

11 views0 comments
bottom of page