Adjust the width of an HTML element as soon as a neighboring element is added

My objective is to achieve automatic resizing of an HTML element.

This is the script I am using:

<html>
    <head>
        <style>
            .main{
                background-color: blue;
                width: 500px;
                position: fixed;
            }
            .inner{
                background-color: brown;
            }
            #tag{
                display: inline;
                background-color: aqua;
            }
            input{
                float: right;
                width: auto;
                height: 100%;
            }
            button{
                margin-top: 30px;
            }
        </style>
    </head>
    <div class="main">
        <div class = "inner">
            <div id="tag">

            </div>
            <input type='text'>
        </div> 
    </div>
    <button onclick="add()">Add</button>
    <script>
        function add(){
            let text = document.getElementById("tag").innerHTML;
            document.getElementById("tag").innerHTML = text+"<span>hi</span>";
        }
    </script>
</html>

Jsfiddle link: https://jsfiddle.net/j0xmkgd8/

The issue I am facing is the inability to achieve auto-resizing of width.

Expected Outputs

  • Initially, the input element should have a full width of 500px.

  • Upon clicking the Add button, the input element's width should resize based on the parent width of 500px with no overflow of elements.

  • For example, if the Add button is clicked once, the 'Hi' text should appear within the 'inner' class element and the input element's width should shrink in accordance with the inner class width (i.e. 50px for inner class element + 450px for input element = 500px for main class element).

    • As the inner class width increases, the input element's width should decrease accordingly.

Answer №1

A fork of the fiddle has been created with additional IDs: https://jsfiddle.net/c4yhv7zk/

<div class="main" id="main">
    <div class = "inner">
        <div id="tag">

        </div>
        <input id="input" type='text'>
    </div> 
</div>

The text input will now adjust its width based on the outer width of the main div and tag div by subtracting their widths. A 5px margin has been added to prevent overflow, hiding the input element if the subtraction result is less than 0.

var tagWidth = document.getElementById("tag").offsetWidth;
var mainWidth = document.getElementById("main").offsetWidth ;
var finalWidth = mainWidth - tagWidth - 5;
if ( finalWidth > 0 ) {
    document.getElementById("input").style.width = finalWidth + "px"; 
} else {
    document.getElementById("input").style.display = "none"; 
}

"box-sizing: border-box" has also been included to prevent browser inconsistencies:

.main{
  background-color: blue;
  width: 500px;
  position: fixed;
  box-sizing: border-box;
}
.inner{
  background-color: brown;
  width: 100%;
  box-sizing: border-box;
}
#tag{
  display: inline;
  background-color: aqua;
  box-sizing: border-box;
}
input{
  height: 100%;
  box-sizing: border-box;
}

To avoid the need for the 5px subtraction, you could use "float: left" and "float: right" on the #tag and #input elements respectively. This change was not applied in this fiddle due to uncertainty about the importance of "display: inline" on the #tag element for your project.

Answer №2

Take a look at the code snippet provided and feel free to reach out if you have any questions.

 .main{
                background-color: blue;
                min-width: 500px;
                position: fixed;
                width:auto;
            }
            .inner{
                background-color: brown;box-sizing
            }
            #tag{
                display: inline;
                background-color: aqua;
            }
            input{
                width: auto;
                height: 100%;
            }
            button{
                margin-top: 30px;
            }
<html>
    <head>
    </head>
    <div class="main">
        <div class = "inner">
            <div id="tag">

            </div>
            <input type='text'>
        </div> 
    </div>
    <button onclick="add()">Add</button>
    <script>
        function add(){
            let text = document.getElementById("tag").innerHTML;
            document.getElementById("tag").innerHTML = text+"<span>hi</span>";
        }
    </script>
</html>

Answer №3

Utilizing Flexbox for dynamic resizing of elements can be quite advantageous. By leveraging its capabilities, you have the ability to occupy the remaining space within a container with an element and adjust the size of the input whenever a new <span> is added to the container.

function add() {
  document.getElementById("tag").insertAdjacentHTML('beforeend', '<span>hi</span>');
}
*, *::before, *::after {
  box-sizing: border-box;
}

.main {
  background-color: blue;
  width: 500px;
}

.inner {
  display: flex;
  background-color: brown;
}

#tag {
  flex: 0;
  background-color: aqua;
}

input {
  flex: 1 1 auto;
  height: 100%;
}

button {
  margin-top: 30px;
}
<div class="main">
  <div class="inner">
    <div id="tag">

    </div>
    <input type='text'>
  </div>
</div>
<button onclick="add()">Add</button>

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

Optimal method for managing errors in Flask when handling AJAX requests from the front end

I'm currently working on a React application that communicates with a Python Flask server. One of the features I am adding allows users to change their passwords. To do this, an AJAX request is sent from React to Flask, containing both the old and ne ...

A method for reversing specific characters within lengthy strings

I'm currently tackling a coding problem: For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string. If there are less than k characters remaining, reverse al ...

Include a div element within the slider

In the process of developing a slider feature that includes both images and paragraphs on each slide, I have encountered a stumbling block while attempting to create a new div element. Despite trying various solutions, the methods that previously worked fo ...

Convert a function into another function when the button is clicked

Hey there, I have an array containing years in my controller: public function getNextYear() { $years = $this->getYears(); foreach ($years as $key => $value) { $y[] = $value + 1; } return $y; } I am displaying this on my ind ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

HTML displaying inaccurately

While following a Ruby tutorial to create a Sample App, I encountered an issue with the signup page. The errors displayed during sign up are not formatted correctly - the period at the end of the error line appears before it, and both the asterisk and bull ...

The button event is currently only targeting the initial class. (Jquery)

I am having an issue where only the first instance of the saveBtn class is being saved into local storage when clicked. Can anyone provide some assistance with this? Here is the HTML: <div class="hour-container" id="8am"> & ...

Tutorials on transferring selected option data to a component

My JSON data is structured like this: Whenever I choose an option, I want to pass the values (code and description) from the JSON object to the component. nameList= [ { "code": "1", "description": "abc" }, { "code": "123", "descript ...

Using UI Bootstrap modal within a directive allows for the functionality of multiple modals, with the unique feature

Check out this Plunkr to see the issue I'm facing with two modals, each within separate directives named modal-one and modal-two. The problem arises when clicking on the button for modal two, as only modal one is being opened. I suspect that the iss ...

Reconstructing the complete pathway using object identifiers

Imagine I have a set of website routes represented by the object below: const routes = { HOME: "start", ACCOUNT: { HOME: "account", PROFILE: "profile", ADDRESSES: { HOME: "addresses", DETA ...

Automatically updating database with Ajax post submission

I have customized the code found at this link (http://www.w3schools.com/PHP/php_ajax_database.asp) to update and display my database when an input box is filled out and a button is clicked to submit. Below is the modified code: <form method="post" acti ...

Is there a way to transmit a value from a page item on the client side to the server side in Oracle Apex without needing to submit the form?

I implemented a JavaScript function to capture the unique ROWIDs of selected rows in the GRID and send them to a specific page item. var gridView = apex.region("emp").call("getCurrentView"), selectedRecords = gridView.getSelectedRec ...

What is the best way to instruct npm to generate a .min.css file from scss?

Currently, I have setup a process to automatically compile CSS from SCSS using a JSON script. However, the issue is that the ".min" suffix is being removed during this compilation. Here is the output from the terminal displaying the script I am running and ...

The width of BootStrap select is not adjusted properly when a prepend is added

Currently, I'm working on designing a login page where I want to include an icon before the select option to indicate that users can change the language. However, when I added the icon, the select width became distorted. It appears a bit too wide on t ...

Enhancing Scroll Speed with Jquery Load More

Experiencing a minor glitch with the code below. It seems to be functioning properly, but an issue arises when users scroll down multiple times before the data loads completely. This can result in the data loading twice or skipping sections. Any suggesti ...

Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure: var lowestPricesCars = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", ...

Display Three.js within a designated div container

I am currently utilizing Three.js. Is it feasible to render in just one div element on an HTML site that contains two div elements? Here is the HTML Code: <body> <div id="twocols"> <div id="detailinfo"> <span ...

Storing Backbone collection data retrieved from a JSON file and persisting it in local storage

I recently started working with the backbone library and exploring building a mobile application using backbone, requirejs, and jquery-mobile. I've successfully populated my collection with data from a local JSON file (with plans to eventually retriev ...

Inquiry regarding the setTimeout function requiring an answer

I have a question about how setTimeout works. Does it wait for the previous code to finish executing before moving on to execute something else after a set time, or does it simply wait for a specific amount of time and then continue with the rest of the co ...

What steps can be taken to ensure a dropdown selection is required when a specific variable is true?

How can I create an AngularJS dropdown that requires a selection only when a specific variable, such as 'x', is set to true? If 'x' is false, it should allow saving without a selection. Below is the code for my dropdown: <select cla ...