Adjust the textboxes' alignment dynamically according to the width of the browser window using Vanilla JavaScript

I'm attempting to adjust the alignment of textboxes as the browser window reaches a specific size. My goal is to have all text boxes and dropdowns align to the right.

I've experimented with tweaking the paddingLeft and marginLeft of the Textbox, as well as adjusting the paddingRight and marginRight of the label.
I even tried setting innerHtml = '&nbsp' and outerHtml = '&nbsp'.
For fun, I attempted using

insertAdjacentHTML('beforebegin', '&nbsp')
for the Textbox and
insertAdjacentHTML('afterbegin', '&nbsp')
for the label.


HTML Below with Embedded Javascript trying to re-align the textboxes:

<!DOCTYPE html>
<html>
  <body> 
    <script type="text/javascript">

        window.onresize = PositionElements();

        function PositionElements() {

            if (document.readyState == 'interactive') {


                var inputAptNumber = document.getElementById('inputAptNumber');

                if (fieldsetElement.clientWidth == 380) {

                    aptElement.innerHTML = '<br />';        

                    /*fix the indentation of the screen*/
                    inputAptNumber.style.marginLeft = '20px';
                }
            }
        }

    </script>
    <h1>Survey</h1>

    <form id="personalInfoForm" runat="server" method="post">
        <div id="nameDiv">

            <!-- Personal Demographic Information -->
            <fieldset id="surveyMainFieldset">
               <legend>Personal Information</legend>
                <div>
                    <span>
                        <label for="inputfirstName" id="labelFirstName">First Name: </label><input type="text" name="firstName" maxlength="50" id="inputFirstName" class="personalInfoInput" placeholder="First name" required="required" runat="server"/>
                    </span>

                    <span>
                        <label for="inputMiddleName" id="labelMiddleName">Middle Name: </label><input type="text" name="middleName" maxlength="50" id="inputMiddleName" class="personalInfoInput" placeholder="Middle name" runat="server"/>
                    </span>

                    <span>
                        <label for="inputLastName" id="labelLastName">Last Name: </label><input type="text" name="lastName" maxlength="50" id="inputLastName" class="personalInfoInput" placeholder="Last name" required="required" runat="server"/>
                    </span>

               </div>

               <div id="localAddressDiv">
                   <span id="streetElement">
                       <label for="inputStreetAddress" class="personalFormLabel" id="labelStreetAddress">Street Address: </label><input type="text" name="streetAddress" maxlength="150" id="inputStreetAddress" class="personalInfoInput" placeholder="Street address" runat="server"/>
                   </span>

                   <span id="aptElement">
                       <label for="inputAptNumber" class="personalFormLabel" id="labelAptNumber">Apt.#: </label><input type="text" name="aptNumber" maxlength="5" id="inputApt" class="personalInfoInput" placeholder="Apt.#" runat="server"/>
                   </span>

                   <span id="cityElement">
                       <label for="inputCity" class="personalFormLabel" id="labelCity">City: </label><input type="text" name="city" maxlength="50" id="inputCity" class="personalInfoInput" placeholder="City" runat="server"/>
                   </span>

                </div>

                <div id="stateAddressDiv">
                    <span id="stateElement">
                        <label for="StateDropdown" class="personalFormLabel" id="labelState">State: </label><select id="StateDropDown" name="stateSelection" runat="server" ></select>
                    </span>

                    <span>
                        <label for="inputZip" class="personalFormLabel" id="labelZip" >Zip code: </label><input type="text" name="zipNumber" maxlength="9" id="inputZip" class="personalInfoInput" placeholder="Zip code" runat="server"/>
                    </span>

                </div>
           </fieldset>
        </div>
    </form>

</body>

CSS Below

#personalInfoForm
{
width: auto;
margin-left: 25px;
margin-right: 25px;
margin-top: 15px;
margin-bottom: 15px;
height: 494px;
}

#personalInfoInput
{
overflow:hidden;
}

#personalInfoForm span
{
padding: 0px 0px 0px 10px;
}

#personalInfoForm #inputStreetAddress
{
width: 150px;
}

#personalInfoForm #inputApt
{
width: 50px;
}

#ageDropDown #childDropDown
{
width: 250px;
}

#localAddressDiv #nameDiv #stateAddressDiv
{
padding-top: 8px;
padding-bottom: 8px;
}

span
{
display:inline-block;
margin-top: 3px;
margin-bottom: 3px;
}

I seem to be missing where the issue lies. Any assistance would be valued.

Answer №1

JavaScript may not be necessary in this scenario. CSS @media queries are designed for situations like these.

@media (max-width: 380px) { /* apply the styles below for screen size up to 380px */
  #personalInfoForm span {
    display: block;
  }

  #personalInfoForm input, #personalInfoForm select {
    float: right;
  }
}

Here's a functional snippet with a media query set to 600px for demonstration purposes:

#personalInfoForm {
  width: auto;
  margin-left: 25px;
  margin-right: 25px;
  margin-top: 15px;
  margin-bottom: 15px;
  height: 494px;
}

#personalInfoInput {
  overflow: hidden;
}

#personalInfoForm span {
  padding: 0px 0px 0px 10px;
}

#personalInfoForm #inputStreetAddress {
  width: 150px;
}

#personalInfoForm #inputApt {
  width: 50px;
}

#ageDropDown #childDropDown {
  width: 250px;
}

#localAddressDiv #nameDiv #stateAddressDiv {
  padding-top: 8px;
  padding-bottom: 8px;
}

span {
  display: inline-block;
  margin-top: 3px;
  margin-bottom: 3px;
}

@media (max-width: 700px) {
  #personalInfoForm span {
    display: block;
  }
  #personalInfoForm input,
  #personalInfoForm select {
    float: right;
  }
}
<h1>Survey</h1>

<form id="personalInfoForm" runat="server" method="post">
  <div id="nameDiv">

    <!-- Personal Demographic Information -->
    <fieldset id="surveyMainFieldset">
      <legend>Personal Information</legend>
      <div>
        <span>
          <label for="inputfirstName" id="labelFirstName">First Name: </label>
          <input type="text" name="firstName" maxlength="50" id="inputFirstName" class="personalInfoInput" placeholder="First name" required="required" runat="server"/>
        </span>

        <span>
          <label for="inputMiddleName" id="labelMiddleName">Middle Name: </label>
          <input type="text" name="middleName" maxlength="50" id="inputMiddleName" class="personalInfoInput" placeholder="Middle name" runat="server"/>
        </span>

        <span>
          <label for="inputLastName" id="labelLastName">Last Name: </label>
          <input type="text" name="lastName" maxlength="50" id="inputLastName" class="personalInfoInput" placeholder="Last name" required="required" runat="server"/>
        </span>

      </div>

      <div id="localAddressDiv">
        <span id="streetElement">
          <label for="inputStreetAddress" class="personalFormLabel" id="labelStreetAddress">Street Address: </label>
          <input type="text" name="streetAddress" maxlength="150" id="inputStreetAddress" class="personalInfoInput" placeholder="Street address" runat="server"/>
        </span>

        <span id="aptElement">
          <label for="inputAptNumber" class="personalFormLabel" id="labelAptNumber">Apt.#: </label>
          <input type="text" name="aptNumber" maxlength="5" id="inputApt" class="personalInfoInput" placeholder="Apt.#" runat="server"/>
        </span>

        <span id="cityElement">
          <label for="inputCity" class="personalFormLabel" id="labelCity">City: </label>
          <input type="text" name="city" maxlength="50" id="inputCity" class="personalInfoInput" placeholder="City" runat="server"/>
        </span>

      </div>

      <div id="stateAddressDiv">
        <span id="stateElement">
          <label for="StateDropdown" class="personalFormLabel" id="labelState">State: </label>
          <select id="StateDropDown" name="stateSelection" runat="server" ></select>
        </span>

        <span>
          <label for="inputZip" class="personalFormLabel" id="labelZip" > ;Zip code: </label>
          <input type="text" name="zipNumber" maxlength="9" id="inputZip" class="personalInfoInput" placeholder="Zip code" runat="server"/> ;
        </span>

      </div>
    </fieldset>
  </div>
</form>

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

Tips for updating the CSS properties of the "html" element

html { width:100%; } Looking to dynamically update the CSS of the html tag upon button click using JavaScript. The goal is to modify the existing HTML CSS code as shown below, but achieving this dynamically with a script. Is it possible? html { w ...

Wait for transition to finish before setting focus to text input

How can I ensure that the focus is automatically set to the text input field after a transition has ended? I want the user's keyboard input to immediately go into the text input field. Is it possible to achieve this using only CSS, or do I need to use ...

Enhancing buttons with CSS styles

Check out the demo .special_button:active { box-shadow: 0px 3px 3px -2px #777; padding: 3px; width:80px; } .button_container { border: 1px solid; width: 100px; padding: 7px; } I'm experimenting with creating spec ...

What is the best way to deactivate the time-based trigger in an old version of a Google sheet, while ensuring it remains active in the duplicated new version?

When I initially copied a Google Sheet, I assumed that the app scripts would be duplicated as well. However, it turns out that this is not the case. Here's the background story: I made a version 2 by copying version 1. Because I wanted to ensure that ...

Tips for displaying a React component with ReactDOM Render

_Header (cshtml) <div id="Help"></div> export default class Help { ReactDOM.render( <Help/>, document.getElementById('Help') ); } Help.js (component) } My objective is to di ...

Sharing data between pages in Ionic and Angular with POST requests

Currently, I am utilizing Ionic for developing a mobile application and have decided to incorporate very basic authentication (without any security measures) into the app. The process involves validating user credentials against a database through a POST r ...

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

Divide using two separators

const inputString = 'db.employee.find({"city":"Paris"},{"emp_id":1}' const result = inputString.split(/\.|\[); // splitting based on . or [ Is there a way to split a string based on two delimiters, such as . and [? For example, if we ...

Using typecasting method to extract value from a JSON object

Struggling with a JavaScript and JSON issue. There's a function that includes a JSON object: blah=function(i){ var hash= ({ "foo" : "bar", "eggs":"bacon", "sausage":"maple syrup" }); var j=eval(hash); // Convert to Object console.log(j.toSou ...

I'm looking to execute a Vue.js method within a template tag and display the data returned by the method. How

Currently, I am in the process of developing a web application using Laravel and Vue.js. As someone who is new to these frameworks, I am facing a challenge where I need to call a method inside a Vue component and display its return data within a v-for loop ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

Mastering the art of integrating HTML5's localstorage feature with Jquery's select2 plugin

Is it possible to integrate HTML5's localstorage method with Jquery's select2 plugin? Currently, all entered data disappears when the browser/tab is closed, leading to potential confusion if you forget what was entered. Here is an example of my ...

Div being visually overtaken by background image

I am struggling to make the image declared in bg fit into the container-fluid without overflowing. You can check out the live example at . The main objective is to position the text on top of the image so that I can apply opacity and blur effects to the i ...

Tips for hiding a class while scrolling up with jQuery

I have been experimenting with making classes appear and disappear based on scrolling behavior in a browser. I successfully made a class appear when reaching a certain height using the following code: jQuery(".tetapElement").css("opacity", 1); jQuery ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

React Highchart issue: The synchronized chart and tooltip are failing to highlight the data points

I am currently utilizing the highchart-react-official library to create two types of charts: 1) Line chart with multiple series 2) Column Chart. My objective is to implement a synchronized behavior where hovering over a point in the first line chart hig ...

Encountered an issue while trying to send an email through the Gmail API: Unfortunately, this API does not provide

I am attempting to use the Gmail API to send emails. I collect user data and convert it to a base64url string. After obtaining the raw value, I attempt to send the email using a POST request. var ss=new Buffer(message).toString('base64') var ...

What could be causing the Custom CSS file to stop functioning properly?

Currently, I am in the process of developing an eCommerce website utilizing PHP, Bootstrap, and JQuery. In order to structure the header file for this project, I have followed the following format: <!DOCTYPE html> <html> <head> ...

How can I save the output of a function in a variable within an *ngIf directive and then utilize it within the same *ngIf block?

My scenario is as follows: I have a function that returns an array I need to conditionally render a component - only if the array exists and its length is greater than zero. The returned array should be passed as an @Input() to this component. Since t ...