Display a maximum of 5 search results at a time in the search bar

I have a search bar that is currently working perfectly, but I am facing an issue. I want only 5 results to be visible at a time, and the remaining results should be seen by sliding from the slider. For example, if there are 10 results, then only 5 should show on searching and users can slide from the slidebar to see the rest. Here is my code:

function filterFunction() {
  let isInputAvailable = false;
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toLowerCase();
  if (filter.length > 0) {
    document.getElementById("myDropdown").classList.add("show");
  } else {
    document.getElementById("myDropdown").classList.remove("show");
  }
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].innerText;
    if (txtValue.toLowerCase().indexOf(filter) > -1) {
      isInputAvailable = true;
      a[i].style.display = "block";
    } else {
      a[i].style.display = "none";
    }
  }
  if (!isInputAvailable) {
    document.getElementById("noMatches").classList.add('show');
  } else {
    document.getElementById("noMatches").classList.remove('show');
  }
}
.div {
  display: none;
}

.dropbtn {
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  border-radius: 25px;
}

#myInput {
  box-sizing: border-box;
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: 5px solid #ddd;
  border-radius: 25px;
}

#myInput:focus {
  outline: 4px solid #f2f2f2;
  border-color: #171313;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: none;
  z-index: 1;
  border-radius: 25px;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<div class="dropdown">
  <input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onInput="filterFunction()">
  <div id="myDropdown" class="dropdown-content">
    <a href="#">Result 1</a>
    <a href="#">Result 2</a>
    <a href="#">Result 3</a>
    <a href="#">Result 4</a>
    <a href="#">Result 5</a>
    <a href="#">Result 6</a>
    <a href="#">Result 7</a>
    <a href="#">Result 8</a>
    <a href="#">Result 9</a>
    <a href="#">Result 10</a>
    <a href="#">Result 11</a>
    <a href="#">Result 12</a>
    <a href="#">Result 13</a>
    <a href="#">Result 14</a>
    <a href="#">Result 15</a>
  </div>
  <div id="noMatches" class="dropdown-content">
    <a href="#tools">No Matches</a>
  </div>
</div>

I want the matching results to be shown when searched, but with a limitation of showing only 5 at a time. There should also be a slider on the right side from which users can slide to view other results. I hope you understand what I'm looking for. Thank you in advance.

Answer №1

Take a look at this code snippet:

function filterFunction() {
    let isInputAvailable = false;
    var input, filter, ul, li, a, i;
    input = document.getElementById("myInput");
    filter = input.value.toLowerCase();
    if (filter.length > 0) {
        document.getElementById("myDropdown").classList.add("show");
    } else {
        document.getElementById("myDropdown").classList.remove("show");
    }
    div = document.getElementById("myDropdown");
    a = div.getElementsByTagName("a");
    for (i = 0; i < a.length; i++) {
        txtValue = a[i].innerText;
        if (txtValue.toLowerCase().indexOf(filter) > -1) {
            isInputAvailable = true;
            a[i].style.display = "block";
        } else {
            a[i].style.display = "none";
        }
    }
    if (!isInputAvailable) {
        document.getElementById("noMatches").classList.add('show');
    } else {
        document.getElementById("noMatches").classList.remove('show');
    }
}
.div {
    display: none;
}

.dropbtn {
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    border-radius: 25px;
}

#myInput {
    box-sizing: border-box;
    background-position: 14px 12px;
    background-repeat: no-repeat;
    font-size: 16px;
    padding: 14px 20px 12px 45px;
    border: 5px solid #ddd;
    border-radius: 25px;
}

#myInput:focus {
    outline: 4px solid #f2f2f2;
    border-color: #171313;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    max-height: 215px;
    display: none;
    position: absolute;
    background-color: #f6f6f6;
    min-width: 230px;
    overflow-y: scroll;
    border: none;
    z-index: 1;
    border-radius: 25px;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown a:hover {
    background-color: #ddd;
}

.show {
    display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
</head>
<body>
    <div class="dropdown">
        <input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onInput="filterFunction()">
        <div id="myDropdown" class="dropdown-content">
            <a href="#">Result 1</a>
            <a href="#">Result 2</a>
            <a href="#">Result 3</a>
            <a href="#">Result 4</a>
            <a href="#">Result 5</a>
            <a href="#">Result 6</a>
            <a href="#">Result 7</a>
            <a href="#">Result 8</a>
            <a href="#">Result 9</a>
            <a href="#">Result 10</a>
            <a href="#">Result 11</a>
            <a href="#">Result 12</a>
            <a href="#">Result 13</a>
            <a href="#">Result 14</a>
            <a href="#">Result 15</a>
        </div>
        <div id=-"noMatches" class="dropdown-content">
            <a href="#tools">No Matches</a>
        </div>
    </div>
</body>
</html>

The maximum height of .dropdown-content has been restricted using the max-height property and vertical overflow set to scroll with overflow-y: scroll;. The overflow: auto from .dropdown-content has been removed.

Answer №2

  • Avoid using IDs in your code, focus on creating reusable programming elements.
  • When displaying dropdowns or toggling between list and no-matches, apply two classes to the parent element (""hasvalue" and "nomatch"). The rest of the styling can be achieved using pure CSS and the :focus selector.
  • Utilize CSS max-height property to control the height of overflow elements effectively.
  • For better user experience, consider truncating the last word in a list item to subtly indicate to users that there are more items in the scrollable section.

function customizedDropdown(EL) {
  const EL_input = EL.querySelector(".dropdown-input");
  const ELS_li = EL.querySelectorAll(".dropdown-box--list a");
  const filter = () => {
    const val = EL_input.value.trim().toLowerCase();
    const fil = [...ELS_li].filter(el => {
      const match = el.textContent.trim().toLowerCase().includes(val);
      el.classList.toggle("hide", !match);
      return match;
    });
    EL.classList.toggle("hasvalue", val.length);
    EL.classList.toggle("nomatch", val.length && !fil.length);
  };

  EL_input.addEventListener("input", filter);
  EL_input.addEventListener("focus", filter);
  ELS_li.forEach(el => el.addEventListener("mousedown", () => {
    EL_input.value = el.textContent.trim()
  }));
}

document.querySelectorAll(".custom-dropdown").forEach(el => customDropdown(el));
/* Reset Default */ * {margin: 0; box-sizing: border-box;}


/* CUSTOM DROPDOWN COMPONENT */

.custom-dropdown {
  --item-height: 30px;
  --visible: 5;
  font-family: sans-serif;
  position: relative;
  display: inline-block;
}

.dropdown-input {
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  font-size: 16px;
  padding: 15px 20px;
  border: 5px solid #ddd;
  border-radius: 25px;
  background: #fff;
}

.dropdown-input:focus {
  outline: none;
  border-color: #000;
}

.custom-dropdown.hasvalue .dropdown-input:focus {
  border-bottom: 1px solid #ddd;
  border-radius: 25px 25px 0 0;
}

.dropdown-box {
  display: none;
  position: absolute;
  top: 100%;
  z-index: 1;
  min-width: 100%;
  overflow: auto;
  border-radius: 0 0 10px 10px;
  max-height: calc(var(--item-height) * var(--visible));
  border: 5px solid #000;
  border-top: 0;
}

.custom-dropdown.hasvalue .dropdown-input:focus~.dropdown-box--list {
  display: block;
}

.custom-dropdown.nomatch .dropdown-input:focus~.dropdown-box--list {
  display: none;
}

.custom-dropdown.nomatch .dropdown-input:focus~.dropdown-box--nomatch {
  display: block !important;
}

.dropdown-box a {
  display: flex;
  align-items: center;
  padding: 7px 20px;
  min-height: var(--item-height);
  color: black;
  text-decoration: none;
  transition: background 0.24s;
}

.dropdown-box a.hide {
  display: none;
}

.custom-dropdown a:hover {
  background-color: #acf;
}

.custom-dropdown::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

.custom-dropdown::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 10px;
}

.custom-dropdown::-webkit-scrollbar-thumb {
  background-color: #000;
}
<div class="custom-dropdown">
  <input type="text" class="dropdown-input" autocomplete="off" placeholder="&#x1F50D;&#xfe0e; Search...">
  <div class="dropdown-box dropdown-box--list">
    <a href="#">Result 1</a>
    <a href="#">Result 2</a>
    <a href="#">Result 3</a>
    <a href="#">Result 4</a>
    <a href="#">Result 5</a>
    <a href="#">Result 6</a>
    <a href="#">Result 7</a>
    <a href="#">Result 8</a>
    <a href="#">Result 9</a>
    <a href="#">Result 10</a>
    <a href="#">Result 11</a>
    <a href="#">Result 12</a>
    <a href="#">Result 13</a>
    <a href="#">Result 14</a>
    <a href="#">Result 15</a>
  </div>
  <div class="dropdown-box dropdown-box--nomatch">
    <a href="#tools"><i>No Matches</i></a>
  </div>
</div>


<div class="custom-dropdown">
  <input type="text" class="dropdown-input" autocomplete="off" placeholder="&#x1F50D;&#xfe0e; Yet another...">
  <div class="dropdown-box dropdown-box--list">
    <a href="#">Lorem</a>
    <a href="#">Ipsum</a>
    <a href="#">Dolor sit amet</a>
    <a href="#">Lorem ut florem</a>
  </div>
  <div class="dropdown-box dropdown-box--nomatch">
    <a href="#tools"><i>No Matches</i></a>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to efficiently load a data table once the page is fully loaded?

Is there a way to load data into a table after the page has finished loading? My page includes a table, a textbox, and a search button. I have been considering using ajax, but have not found a suitable solution yet. What is the best approach for this - J ...

The amazing magnific popup boasts a pair of close buttons

I recently started working on integrating a front-end HTML theme with a back-end Laravel app. Oddly enough, I noticed that the popup modal is displaying two close x buttons instead of just one. Despite my efforts, I have been unable to pinpoint what exactl ...

Prevent further clicking on a button in a custom Drupal module after it has been clicked three times

I'm new to using Drupal and have created a custom module similar to webform. In my module page, I have two submit buttons and 2 textboxes as shown below: function contact_request($form, &$form_state) { $form ['info'] =array( &ap ...

Combining THREE.Sprite with fog or utilizing THREE.ParticleSystem with an array of texture maps

Currently attempting to create a particle system using Sprite, however, encountering an issue where Sprite does not appear to respond to the "fog" parameter, meaning it does not fade away with distance. While ParticleSystem does adhere to the fog parameter ...

When attempting to call a recursive method in Vue with a changing `this` object, an error is thrown: "RangeError: Maximum call stack size exceeded"

Update integrate codePen into the project. https://codepen.io/jiaxi0331/pen/xxVZBMz Description encountered an issue while trying to call the parent method recursively Code export default { methods: { dispatch(componentName, event, value) { ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

In JavaScript, when a div element contains an iframe, the click event will not trigger on the div

Check out this sample HTML markup: <div> <iframe></iframe> </div> The iframe is set to fill the outer div. I've added an event handler to the div click event: div.addEventListener("click", function () { console.log( ...

JavaScript function fails to execute when attempting to call it after opening email client with attachment

//deliver the email to the recipient in eml format Response.ClearHeaders(); Response.Clear(); Response.Buffer = true; Response.ContentType = "message/rfc822"; Response.AddHeader("content-length", bin.Length.ToString()); Response.AddHead ...

The disappearance of a JavaScript click event within an update panel

I have a situation where I am using an asp.net updatepanel that contains three dropdowns and a submit button. Using javascript, I bind a "click" event to the submit button to capture the values of the dropdowns. However, when I select a new value from a dr ...

Experiencing a problem with a loop in iMacros/JS?

I have an iMacros/JS script for Facebook that logs into a FB account from a CSV file, then it has a second loop j which sends 20 friend requests from each account. The issue arises when switching accounts and encountering a popup message requiring phone n ...

Error in Node.js: Cannot listen on socket.io object as it does not have a 'listen' method

I am currently developing a Node application using socket.io version 0.9.13 alongside Express 3.0.6. I am encountering an issue where the app fails to run due to an error stating that socket.io does not have a method called listen(). Here is the code snipp ...

What is the most efficient way to move queried information from one table to another while maintaining all data entries?

Currently, I am working on a small POS project. In this project, I have two tables. The main purpose of the first table is to retrieve products from a search box with two column names retrieved from the database. If the products are found, I want to be abl ...

Populate DataTable with HTML content by fetching it through Ajax requests

My goal is to dynamically load the HTML returned from a controller into a div when a user clicks on a row in a table. Check out my code snippet below: // Add event listener for opening and closing details jQuery('#exRowTable tbody').on ...

Is there a way to eliminate duplicate elements from 2 arrays in Angular?

Imagine I have a scenario with two arrays: arr1 = ["Tom","Harry","Patrick"] arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"] Is it possible to eliminate the duplicate elements in these arrays? The desired output would be: arr2 = ["Miguel"," ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

Is there a simpler method to enable built-in CSS-Sass in Next.js without the need for excessive configuration?

Is there a way to maintain the built-in CSS/SASS feature in Next.js without extensive configuration? Utilizing the built-in CSS/SASS is convenient, but introducing less to next.config.js triggers the disabling of this feature, requiring manual configurati ...

Invoking functions with JavaScript objects

Can anyone help me figure out what is wrong with the following JavaScript code? <form> What is 5 + 5?: <input type ="number" id ="num_answer;"/> </form> <script> function basic_math(){ var num_val = document.getElem ...

Issue within the application causing a sudden shutdown

I have been encountering an application error in my android phonegap app. The issue arises when I transition from one page to another page, resulting in the following message: "A network error occurred.(file:///android_asset/www/home/home.html?userid=91 ...

AJAX call terminated; success signal triggered prematurely

Looking for help with a method that deletes a town through jQuery and Ajax. Check out the code below: <button class="btn btn-danger btn-sm" onClick="deleteTown(@item.TownId)"><i class="fa fa-trash"></i></button></a> Delete T ...

Tips for inserting a PHP variable into a Bootstrap CCS class to change the background image dynamically

I currently have CSS code set up for a full background image. I am now looking to dynamically change the background image by passing a PHP variable to the URL. Can someone please help me with this? Here is my current code: .imgback { padding-top:140px; ...