Javascript Issue: Difficulty Implementing Item List Container

Is there a way to adjust the list so that it only expands the container from the bottom, causing a scrollbar to appear?

LINK TO CODE EXAMPLE: https://codepen.io/Redd_1/pen/qBZWJQG

Answer №1

To ensure that newly added items stay within the ul and do not affect the whole container, you can simply set the height on the ul element and apply overflow-y: auto.

Check out this Demo:

// Add item to list
var form = document.getElementById('addForm');
var itemList = document.getElementById('items');

form.addEventListener('submit', addItem);

function addItem(e) {
  e.preventDefault();

  // User input
  var newItem = document.getElementById('item').value;

  document.getElementById('item').value = '';

  if (newItem == '') {
    alert('Please enter some value.');
  } else {
    // Adding values to the list
    var li = document.createElement('li');
    li.className = 'list-group-item';
    li.appendChild(document.createTextNode(newItem));

    // Add a delete button
    var deletebtn = document.createElement('button');
    deletebtn.className = 'btn';
    deletebtn.appendChild(document.createTextNode('X'));

    // Append button and li to the ul
    li.appendChild(deletebtn);
    itemList.appendChild(li);
  }

}


// Remove item from list
itemList.addEventListener('click', removeItem);

function removeItem(e) {
  if (e.target.classList.contains('btn')) {
    if (confirm('Are you sure you want to delete the item?')) {
      var li = e.target.parentElement;
      itemList.removeChild(li);
    }
  }
}

// Search items
var filter = document.getElementById('filter');

filter.addEventListener('keyup', filterItems);

function filterItems(e) {
  var text = e.target.value.toLowerCase();
  var items = itemList.getElementsByTagName('li');

  Array.from(items).forEach(function(item) {
    var itemName = item.firstChild.textContent;
    if (itemName.toLowerCase().indexOf(text) != -1) {
      item.style.display = 'block';
    } else {
      item.style.display = 'none';
    }
  })
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Montserrat;
}

header {
  background-color: green;
  color: white;
  margin: 0;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.container {
  padding: 20px;
  position: fixed;
  width: 500px;
  left: 50%;
  top: 55%;
  transform: translate(-50%, -50%);
  line-height: 40px;
  border: 1px solid black;
  border-radius: 10px;
}

ul {
  overflow-y: auto;
  list-style: none;
  padding: 10px;
  height: 10em;
}

.list-group-item {
  border: 1px solid grey;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
}

.btn {
  background-color: red;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 6px;
}

.sbtn {
  color: white;
  background-color: rgb(46, 46, 46);
  text-transform: uppercase;
  cursor: pointer;
  border: none;
  padding: 8px;
}

.sbtn:hover {
  background-color: black;
}

button {
  float: right;
}

input[type=text] {
  padding: 5px;
}
<!DOCTYPE html>
<html>

<body>
  <link rel="stylesheet" href="itemApp.css">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap" rel="stylesheet">

  <header>
    <h1>Item lister</h1>
    <input type="text" class="search-bar" placeholder="Search items..." id="filter">
  </header>


  <div class="container">
    <h3>Add items</h3>
    <form id="addForm" name="myForm">
      <input type="text" id="item" name="textField">
      <input type="submit" class="sbtn" value="submit">
    </form>

    <h3>Items</h3>
    <ul id="items">
      <li class="list-group-item">Item 1 <button class=btn>X</button> </li>
      <li class="list-group-item">Item 2 <button class=btn>X</button> </li>
      <li class="list-group-item">Item 3 <button class=btn>X</button> </li>
      <li class="list-group-item">Item 4 <button class=btn>X</button> </li>
    </ul>
  </div>

  <script src="itemApp.js"></script>
</body>

</html>

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

Updating AngularJS: Removing the hashtag using history.pushState()

Struggling to enhance the aesthetics of the URLs in my AngularJS application, I am facing some challenges. While I can access the "/" route without any issues, the "/about" route seems to be out of reach. Please note that the project is situated at (loc ...

To interact with a dynamic div that is generated without any specific ID or class, which is contained within a fixed div, you can

Is there a way to trigger a click function using JQUERY on the div that includes the text "Save as JPEG"? The div with the ID "graph1" remains static while all other nested divs are dynamic. Please note that the dynamic div containing the text does not h ...

disabling swap button icons temporarily in Angular 16

I need assistance creating a function that removes an icon from a button and replaces it with a spinner provided by primeng. The function should only remove the child element. Code snippet for the button: <p-button label="" [loading]="lo ...

picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map. My goal is to be able ...

Syntax for making an Ajax call

Encountering an issue with my simple ajax post - data is not being passed successfully to the file (ajaxpost.php). Even though it posts to the file, the POST data is unavailable. var myKeyVals = {caption: "test"}; $.ajax({ //Ex ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Oh no! "The accuracy of your BMI calculation is in question."

I am currently working on a technical assessment for a BMI calculator, but I am facing a challenge in implementing the formula. The instructions for calculating BMI are as follows: Step 1: The user's height is given in feet, so it needs to be conver ...

Reorder the Polymer dom-repeat element following a modification in the child component's value

My Polymer dom-repeat list is working fine on the initial value sorting for the children. However, when I update a value within a child element, the sort order of the list does not reflect the changes. What is the best way to achieve this? <body> ...

Displaying user input data in a separate component post form submission within Angular

I recently developed an employee center app with both form and details views. After submitting the form, the data entered should be displayed in the details view. To facilitate this data transfer, I created an EmployeeService to connect the form and detail ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

IE9 causing issues with Angularjs ng-route - views fail to display

I am new to AngularJS and currently working on developing an application using AngularJS along with Coldfusion for database data retrieval. However, I am facing compatibility issues specifically with IE9 (which is the default browser in my office). The ap ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Angular application enhancing Vaadin web components with unique styling

I've been trying to integrate a Vaadin web component into my Angular application. Following the instructions provided in the documentation at: After setting up everything and installing the required component (vaadin-date-picker) from npm, I succe ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Methods for adding information to a database without using HTML form tag

This is the creation of my design... And here is the snippet of my HTML code... <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> <!-- Form fields for dealer information --> < ...

Ways to ensure a ul li element perfectly fits inside a div element without any spaces

As a newcomer to CSS and HTML, I'm facing an issue with my ul li dropdown menu and login boxes. The background colors are red and blue, but there are gaps within the div that I want to fill with the height of the div. Below is the code snippet: @key ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

Tips for managing and loading data into a dataGrid or table with the help of ReactJS and ReactHooks

Struggling to retrieve user input data from the form and display it in the table/Datagrid below, without success. Follow the process flow outlined below Once the user submits the form and clicks the send now button, the {handleSubmit} function is trigger ...

When a legend is clicked, it should display only the selected item while hiding all other legends automatically in a chart created

I have a highchart with 10 legends. When I click on the first legend, only that legend should remain visible while the rest are automatically hidden... Below is a code snippet with two legends: $(function() { var chart = $('#container').hig ...