What are some strategies for containing elements within a parent div to prevent them from overflowing when new elements are dynamically added

Situation: I am currently working on a project that involves creating a dynamic input box where users can add words that are displayed individually in bubbles. To achieve this, I am attempting to have a div container placed side by side with an input field. The goal is for the user to add elements and see them drop seamlessly into the div container next to the input field. If you need clarification on what I'm aiming for, feel free to check out the reference jsfiddle.

My Issue: The problem arises when adding an element to the div container, causing it to exceed the allocated maximum size that I initially set. I believe the root of the issue lies in the width=100% attribute used for the input box, as it references the parent div which remains static despite the addition of new elements. How can I ensure that the input text box dynamically adjusts its size to fill the remaining space without exceeding it?

My goal: My objective is to find a way for the input box to resize dynamically and fit perfectly within the parent container when sibling elements are added alongside it.

Any assistance or guidance on this matter would be highly appreciated.

Code Snippet:

$('.emotionsInput').keypress(function (e) {
    var key = e.which;

    if (key == 13)
    {
        var inputWord = $(this).val();
        var currentCell = $(this);
        createTag(currentCell);
    }
})

function createTag(currentCell)
{
    var parentCell = currentCell.parent()

    var inputWord = currentCell.val();

    currentCell.val("");
    var newTagHTML = '<span class="emotionTag">' + inputWord + '</span>';
    parentCell.children(".emotionTagsDiv").append(newTagHTML);
}
#testTagBox > span > span {
    border-color:transparent;
    box-shadow:0 0 0 2px #000;
    border-radius: 40px;
    padding:5px;
    background-color: white;
    width: 100%;
    display:flex; 
}

#testTagBox > span {
    padding: 0.67rem 0.5rem;
    width: 100%;
    display:flex;  
}

#testTagBox {
    width: 30rem;
    padding-right:1.8rem;
}

.emotionsDiv {
    display: flex; 
    width: 100%;
    white-space: nowrap;
}

.emotionTagsDiv {
    flex: 1 1 auto; 
    white-space: nowrap;
}

.emotionTag {
    display: inline-block;
    padding-right: 1em;
}

input {
    font-family: Arial;
    display: flex; 
    flex: 20 1 auto; 
    width: 100%;
}

input:focus {
    outline: none;
}
<html lang="en">
<body>
    <div id="testTagBox">
        <span>
            <span>
                <div class="emotionsDiv">
                    <div class="emotionTagsDiv">

                    </div>
                    <input class="emotionsInput" placeholder="type and press enter here" type="text" value="">
                </div>
            </span>
        </span>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.min.js"></script>
    <script src="https://unpkg.com/tippy.js@6/dist/tippy-bundle.umd.js"></script>
    <script src="testapp.js" type="text/javascript" ></script>
</body>
</html>

As depicted in the code snippet, the entire container undergoes resizing when adding an element instead of just the input box adjusting its size to maintain the original dimensions of the parent container while accommodating all elements seamlessly.

Answer №1

To adjust the width of the input, you can modify the display property of .emotionTagsDiv to flex

$('.emotionsInput').keypress(function (e) {
    var key = e.which;

    if (key == 13)
    {
        var inputWord = $(this).val();
        var currentCell = $(this);
        createTag(currentCell);
    }
})

function createTag(currentCell)
{
    var parentCell = currentCell.parent()

    var inputWord = currentCell.val();

    currentCell.val("");
    var newTagHTML = '<span class="emotionTag">' + inputWord + '</span>';
    parentCell.children(".emotionTagsDiv").append(newTagHTML);
}
#testTagBox > span > span {
    border-color:transparent;
  
 
    padding:5px;
    background-color: white;
    width: 100%;
}

#testTagBox > span {
    padding: 0.67rem 0.5rem;
    width: 100%;
}

#testTagBox {
    max-width: 30rem; 
    padding-right:1.8rem;
}

.emotionsDiv {
    display: flex;
    width: 100%;
      box-shadow:0 0 0 2px #000;
     padding: .5rem;
       border-radius: 40px;
}

.emotionTagsDiv {
    display: inline-block;
    white-space: nowrap;
}

.emotionTag {
    display: inline-block;
    padding-right: 1em;
}

input {
    /* border-style: hidden; */
    font-family: Arial;
    display: inline-block;
    width: 100%;
    min-width: 50px; 
}

input:focus {
    outline: none;
}
<html lang="en">
<body>
    <div id="testTagBox">
        <span>
            <span>
                <div class="emotionsDiv">
                    <div class="emotionTagsDiv">

                    </div>
                    <input class="emotionsInput" placeholder="type and press enter here" type="text" value="">
                </div>
            </span>
        </span>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.min.js"></script>
    <script src="https://unpkg.com/tippy.js@6/dist/tippy-bundle.umd.js"></script>
    <script src="testapp.js" type="text/javascript" ></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

Issue with Ajax not functioning properly for Jquery autocomplete feature in PHP

The ajax request shown below is creating an array of values that I want to use in a jQuery autocomplete function: var whatever = []; $.ajax({ url: "myScript.php", success: function (response) { whatever = response.split(","); } }); Th ...

showcasing JSON data in an HTML table with pure JavaScript

I am currently utilizing vanilla JS to send a client request to a REST web service that I have designed. The GET method I have implemented returns a list of books (List) in JSON format: 0: {name: "To Pimp a Butterfly", isbn: "ACBCDDSA", availableCopies: 1 ...

Is jquery.validate necessary for Unobtrusive validation in .NET 4.5?

Currently, I am developing a project using ASP.NET web forms and I am a bit unsure about which jQuery libraries are required for the .NET 4.5 unobtrusive validation. Some sources suggest that I need to include just jquery, while others recommend adding j ...

jQuery Autocomplete with Link Options

Can anyone help me with creating a search function for my charity's internal website? I've managed to get it partially working, but I'm struggling to make the results link to the right places. Below is the code I have so far, including test ...

Receiving Null Value Upon Asynchronous API Call Before Data Retrieval

Struggling with Fetching and Displaying API Data in a Table I am facing a challenge where I need to fetch an API multiple times and populate the data into a table. The issue arises when the data for a specific year is not available, causing the table to b ...

Why does jQuery.extend serve as a jQuery function attribute while jQuery.fn.extend is designated as a jQuery prototype property?

jQuery is described as a function jQuery.extend is defined as a function property and acts as a function itself - however, it is not accessible within any this context. jQuery.fn.extend is designated as a prototype object property, making it available wi ...

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

CSS-enabled tabs built with React

Currently, I have a setup with 5 divs and 5 buttons where only one div is visible at a time when its corresponding button is clicked. However, I am looking for suggestions on how to improve the efficiency and readability of my code. If you have any best pr ...

There seems to be an issue with the Google reCAPTCHA login, as it is displaying an error with the code 'invalid-input-secret'

Customer Interface: grecaptcha.ready(function() { grecaptcha.execute('6Le4oroZABBXXIQCQkAYCXYSekNQnWExTeNUBZ-B', {action: 'submit'}).then(function(token) { $scope.userData['repatcha_token'] = token $ht ...

Ways to determine whether an element is presently engaged in scrolling

Is there a way to determine if certain actions can be disabled while an element is being scrolled? The scrolling may be triggered by using the mouse wheel or mouse pad, or by calling scrollIntoView(). Can we detect if an element is currently being scroll ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

The absence of transpiled Typescript code "*.js" in imports

Here is an example of the code I am working with: User.ts ... import { UserFavoriteRoom } from "./UserFavoriteRoom.js"; import { Room } from "./Room.js"; import { Reservation } from "./Reservation.js"; import { Message } from ...

Having trouble with iterating through nested array objects in Angular 4 component

I am facing an issue when attempting to iterate over a nested array object using the code below. It seems to be throwing an error saying "undefined". Could this be related to Typescript or angular4? import { Process, Event } from "./process"; export clas ...

populating all available space in layouts using bootstrap columns

I am attempting to create a grid layout using bootstrap, but I am facing an issue with positioning one of the columns. I have tried adjusting the placement of the divs and using offsets/pulls, but so far I have not been successful. To explain what I am a ...

Retain the formatting of HTML while extracting the text

Is there a simple way to extract text from HTML source without losing formatting (such as line breaks and spaces)? Currently, my text extraction process looks like this: page_title_element = driver.find_element_by_xpath("x-path") page_title = pa ...

Obtain the value for every span class and insert the corresponding string into the input field

I have a series of tags labeled as 'tag-label' in spans. My goal is to combine the values of these tags and insert them into an input field, separating each value with commas. To demonstrate this, I've created a JSFiddle that showcases the ...

Bootstrap dropdown menu with Javascript List group

<div class="btn-group"> <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria- expanded="false"> Sort <s ...

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

The requested external js scripts could not be found and resulted in a net::ERR_ABORTED 404 error

import express, { Express, Request, Response } from 'express'; const path = require("path"); import dotenv from 'dotenv'; dotenv.config(); const PORT = process.env.PORT || 5000; const app = express(); app.use(express.static(path.join ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...