Form elements change when focused on text boxes

I am attempting to replicate the materialize style for input boxes where the label moves up and decreases in font size with animation when the text box is clicked.

Although I have managed to achieve this effect, there seems to be a slight issue. When clicking on the input box, not only does the label move up as intended, but there is also some noticeable fluctuation happening as if the form elements are shifting by 2px.

How can I fix this? Here is my current code:

$(document).ready(function(){
        $("input").focus(function(){
            $(this).parent().find("label").addClass('active_text_field');
        });

        $("input").focusout(function(){
            if ($(this).val() == '') {
                $(this).parent().find("label").removeClass('active_text_field');
            };
        }); 
})
.contact_form{  
    position: absolute;
    display: block;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 50%;
    height:500px;
}

.form-item label{
    display: block;
    font-size: 18px;
    font-family: roboto;
    position: relative;
    top: 30px;
    -moz-transition: all ease-in-out 200ms;
    -webkit-transition: all ease-in-out 200ms;
    transition: all ease-in-out 200ms;
}

.form-item input{
    width:100%;
    outline:none;
    height:36px;
    border:none;
    border-bottom: solid black 1px;
}

.active_text_field{
    transform: translateY(-30px);        
    -moz-transition: all ease-in-out 200ms;
    -webkit-transition: all ease-in-out 200ms;
    transition: all ease-in-out 200ms;
    font-size: 16px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="contact_form">
    <form>
        <div class="form-item">
            <label for="firstName">
                First Name
            </label>
            <input type="text" name="firstName" class="text-field">
        </div>

        <div class="form-item">
            <label for="lastName">
                Last Name
            </label>
            <input type="text" name="lastName" class="text-field">
        </div>

        <div class="form-item">
            <label for="email">
                Email
            </label>
            <input type="text" name="email" class="text-field">
        </div>

        <div class="form-item">
            <label for="confirmEmail">
                Confirm Email
            </label>
            <input type="text" name="confirmEmail" class="text-field">
        </div>
    </form>
</div>

Answer №1

To achieve the desired effect, it is recommended to utilize proper CSS styling for the position attribute. You can refer to this JSFiddle link for a visual representation of what you are aiming for in your code.

Furthermore, ensure that you set the display property of your label elements to inline-block. This will improve the positioning of the labels when clicked next to an input box.

Here is the HTML Code snippet:

<div class="contact_form">
    <form>
        <div class="form-item">
            <label for="firstName">
                First Name
            </label>
            <input type="text" name="firstName" class="text-field">
        </div>

        <div class="form-item">
            <label for="lastName">
                Last Name
            </label>
            <input type="text" name="lastName" class="text-field">
        </div>

        <div class="form-item">
            <label for="email">
                Email
            </label>
            <input type="text" name="email" class="text-field">
        </div>

        <div class="form-item">
            <label for="confirmEmail">
                Confirm Email
            </label>
            <input type="text" name="confirmEmail" class="text-field">
        </div>
    </form>
</div>

For styling, here is the CSS Code block:

.contact_form{  
    position: absolute;
    display: block;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 50%;
    height:500px;
}

.form-item {
    margin-bottom: 20px;
    position: relative;
}

.form-item label{
    display: inline-block;
    font-size: 18px;
    font-family: roboto;
    position: absolute;
    top: 10px;
    -moz-transition: all ease-in-out 200ms;
    -webkit-transition: all ease-in-out 200ms;
    transition: all ease-in-out 200ms;
}

.form-item input{
    width:100%;
    outline:none;
    height:36px;
    border:none;
    border-bottom: solid black 1px;
}

.active_text_field{
    transform: translateY(-30px);        
    -moz-transition: all ease-in-out 200ms;
    -webkit-transition: all ease-in-out 200ms;
    transition: all ease-in-out 200ms;
    font-size: 16px !important;
}

Lastly, apply the following JavaScript Code:

$(document).ready(function(){
        $("input").focus(function(){
            $(this).parent().find("label").addClass('active_text_field');
        });

        $("input").focusout(function(){
            if ($(this).val() == '') {
                $(this).parent().find("label").removeClass('active_text_field');
            };
        }); 
});

Answer №2

To prevent the fluctuation, one solution is to set the label as absolute positioned relative to its parent container. This can be achieved by adjusting the CSS without the need to modify the HTML or JavaScript code.

For a clearer demonstration, I have prepared a JsFiddle link: [https://jsfiddle.net/axesvL1q/1/]

.contact_form {
      position: relative;
      display: block;
      margin: auto;
      width: 50%;
      height: 500px;
    }

    .form-item label {
      display: block;
      font-size: 18px;
      font-family: roboto;
      position: absolute;
      left: 0;
      top: 0;
      -moz-transition: all ease-in-out 200ms;
      -webkit-transition: all ease-in-out 200ms;
      transition: all ease-in-out 200ms;
    }

    .form-item {
      position: relative;
      margin: 30px 0;
    }

    .form-item input {
      width: 100%;
      outline: none;
      height: 36px;
      border: none;
      border-bottom: solid black 1px;
    }

    .active_text_field {
      transform: translateY(-20px);
      -moz-transition: all ease-in-out 200ms;
      -webkit-transition: all ease-in-out 200ms;
      transition: all ease-in-out 200ms;
      font-size: 16px !important;
    }

Answer №3

If you're looking to solve the issue without relying on JavaScript, CSS can do the trick for floating labels:

Take a look at this code snippet:

.field-container {
  position: relative;
  width: 200px;
  margin-top: 20px;
  font-family: 'Roboto', sans-serif;
}

.field {
  display: block;
  width: 100%;
  padding: 15px 10px 0;
  border: none;
  font-size: 14px;
}

.field:focus {
  outline: 0;
}

.floating-label {
  position: absolute;
  pointer-events: none;
  top: 5px;
  left: 10px;
  font-size: 10px;
  opacity: 0;
  background-color: white;
  padding: 0 2px;
  -webkit-transition: 0.2s ease-in-out;
  transition: 0.2s ease-in-out;
}

.field:valid+.floating-label {
  opacity: 1;
  top: -5px;
  color: #9e9e9e;
}

.field:focus+.floating-label {
  color: #03a9f4;
}

.field-underline {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: -5px;
  border: 1px solid #9e9e9e;
  z-index: -1;
  padding: 10px 10px 0;
}

.field:focus+.floating-label+.field-underline {
  border-color: #03a9f4;
}
<div class="field-container">
  <input type="text" class="field" required placeholder="First name" />
  <label class="floating-label">First name</label>
  <div class="field-underline"></div>
</div>
<div class="field-container">
  <input type="text" class="field" required placeholder="Last name" />
  <label class="floating-label">Last name</label>
  <div class="field-underline"></div>
</div>

Source:floating labels using css

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

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

What is the best way to execute npx commands without the need to add 'npx' before each

For instance, I am able to simply run gulp instead of having to type npx gulp. I can skip the npx and just use gulp How can I achieve this for my own package? Even though I've included mycommand in the package npm bin configuration, I still constan ...

What methods can I use to retrieve traversed objects using riak-js?

Utilizing Node with riak-js to interact with a Riak database. I have established two buckets named invites and events. The invites bucket contains a link to events. Is there a way to fetch both the invite object and the corresponding event object in one qu ...

Guide to populating a select-option dropdown using CSS

I'm working on creating a dropdown menu in HTML that pulls the options from a CSS file. To accomplish this, I have assigned custom classes to each option and specified the option label in the CSS using the CUSTOM_CLASS::after{content: "";} r ...

The cookie appears in the callback URL, but does not get stored in the browser's cookie storage

I'm attempting to store the facebookPicUrl image in a cookie. Even though I can see it in the callback request, it's not showing up in the browser's cookie storage. Just to clarify, the session cookie is working fine. auth.route('/auth ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

Issue with Uploadify causing a 500 error even after successful file upload to the server

Currently, I am working with the Kohana3 framework and integrating the Uploadify plugin for Ajax file uploads. The issue I am facing is that when attempting to upload a file, Uploadify displays a 500 error message. However, upon checking my download folde ...

Is it possible to generate two output JSON Objects for a JavaScript line chart?

How can I display two lines in a Chart.js line chart using data from a JSON file with 2 objects stored in the database? When attempting to show both sets of data simultaneously, I encountered an issue where the output was always undefined. Why is this hap ...

Guide on implementing gradient animation effects in a React component

How can I implement gradient animation effects like this example in a React component using inline CSS? I need to utilize the CSS-based gradient animation effects shown below directly within the React component. Are there any specific packages available ...

Why do CSS changes in Chrome Console only take effect locally and not when the website is live?

I recently encountered an issue where I wanted to incorporate negative margins into a specific section of my website, as seen in the Chrome Console (link to image): .woocommerce div.product div.images .woocommerce-product-gallery__wrapper { -webkit-tr ...

Spinner in BlockUI fails to load

I am facing an issue on my webpage where I use 'blockUI' plugin from Malsup to display a modal message with a spinner when a user clicks a button. $('#btnSend').click(function () { $.blockUI({ message: '<h4><img src=" ...

Higher Order Component for JSX element - displaying JSX with wrapped component

I am looking to utilize a ReactJS HOC in order to implement a tooltip around JSX content. The function call should look similar to this: withTooltip(JSX, "very nice") To achieve this, I have created the following function: import React from "re ...

Changing the position of a Bootstrap popover dynamically from top to bottom

Struggling with the bootstrap popover here. I can't seem to change the popover position from top to bottom when it reaches the top of the viewport. I attempted to use placement: 'auto bottom' but unfortunately, it didn't do the trick f ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Verify the presence of both class and id before modifying the content of the h1 tag and automatically redirecting the page

I'm encountering some issues triggering my JS/JQ on an HTML5 page. Essentially, I want to verify the existence of the following ID and class: ID: page_blog CLASS: page current <section class="page current" id="page_blog" style="z-index: 99; lef ...

What is the reason for the improper setting of the div position?

Welcome to the interactive Pointer Pin application! The red-bordered box is where you can drop your Pointer Pins. This area has a background image set. The blue-bordered box is where you can drag various Pointer Pins from. These pins can be dropped into ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

Implement Material-UI Higher Order Components in a Class-based Component

I'm in the process of incorporating material UI into my class component rather than converting everything to Hooks. I'm unsure which approach would be simpler, utilizing Hooks or adapting what I currently have. https://material-ui.com/styles/bas ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Having difficulty retrieving JSON data using Jquery

After receiving a JSON string as a response from the server, I encountered an issue when trying to access the objects within the response, only to receive an "undefined" message. Here is the AJAX request being made: $.ajax({ url: 'somefi ...