Prevent floating labels from reverting to their initial position

Issue with Form Labels

I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our developers are not familiar with how to do so. As a solution, I have managed to get the labels to move up when the input field is in focus. However, I am facing a problem where after entering information into an input field and moving on to the next one, the field loses focus and the labels revert back to their original position as if they were placeholder text.

Question:

Is there a way using JavaScript (jQuery is acceptable) to detect content within the input fields and keep the labels in their shifted position based on that information?

Note that this functionality should be driven by the input content - meaning that if a user clicks on the input field, types something but then deletes it or simply tabs through without typing anything, the label should return to its placeholder position. While this may seem unnecessary for a login form where both fields are required, I am considering implementing this feature across the entire site for a better user experience.

This is what I have implemented:

HTML

<div class="container">
    <div class="col-xs-4 col-xs-push-4 martop50">
        <div class="login-content">
            <h4 class="text-center m-t-0 m-b-20">Great to have you back!</h4>
            <form action="home.html" method="POST" name="login_form" class="form-input-flat">
                <div class="form-group">
                    <div class="float-labels">
                        <div class="input-group">
                            <span class="input-group-addon left"><i class="fa fa-fw fa-lg fa-user"></i></span>
                            <input type="text" class="form-control input-lg">
                            <label for="user">Username</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="float-labels">
                        <div class="input-group">
                            <span class="input-group-addon left"><i class="fa fa-fw fa-lg fa-lock"></i></span>
                            <input type="password" class="form-control input-lg">
                            <label for="user">Password</label>
                        </div>
                    </div>
                </div>
                <div class="row m-b-20">
                    <div class="col-md-12">
                        <button type="submit" class="btn btn-default btn-lg btn-block">Sign in to your account</button>
                    </div>
                </div>
                <div class="text-center">
                    <small>Problems loging in? </small><a href="register.html" class="text-muted">Contact Support</a>
                </div>
            </form>
        </div>
    </div>
</div>

CSS

.martop50 {
    margin-top: 50px;
}

.login-content, .login .login-content {
    padding: 25px 30px;
    -webkit-border-radius: 0 0 8px 8px;
    -moz-border-radius: 0 0 8px 8px;
    -ms-border-radius: 0 0 8px 8px;
    border-radius: 0 0 8px 8px;
    background: #101113;
    box-shadow: 0 2px 0 #000;
}

h4{
    color: rgba(248,151,29,0.77);
}
.form-input-flat .input-group-addon.left {
    background: #30373e;
    border: 2px solid #8f8f8f;
    color: #bbb;
    border-right: none;
    -webkit-border-radius: 50% 0 0 50%;
    -moz-border-radius: 50% 0 0 50%;
    -ms-border-radius: 50% 0 0 50%;
    border-radius: 50% 0 0 50%;
    padding: 8px 10px 5px 13px;
}
.form-input-flat .input-group-addon {
    background: #30373e;
    border: 2px solid #8f8f8f;
    color: #bbb;
    border-left: none;
    -webkit-border-radius: 0 50% 50% 0;
    -moz-border-radius: 0 50% 50% 0;
    -ms-border-radius: 0 50% 50% 0;
    border-radius: 0 50% 50% 0;
    padding: 0 13px 0 10px;
}

.input-group .form-control:not(:first-child):not(:last-child), .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child) {
    border-radius: 0 34px 34px 0;
}

.form-control {
    border-width: 2px;
    border-color: #8f8f8f;
    -webkit-box-shadow: none;
    box-shadow: none;
    color: #bbb;
    -webkit-border-radius: 34px;
    -moz-border-radius: 34px;
    -ms-border-radius: 34px;
    border-radius: 34px;
    background: #211E1E;
}

.float-labels label {
    font-size: 15px;
    line-height: 18px;
    font-weight: 500;
    position: absolute;
    z-index: 2;
    left: 65px;
    top: 35px;
    padding: 0 2px;
    pointer-events: none;
    background: transparent;
    -webkit-transition: -webkit-transform 100ms ease;
    -moz-transition: -moz-transform 100ms ease;
    -o-transition: -o-transform 100ms ease;
    -ms-transition: -ms-transform 100ms ease;
    transition: transform 100ms ease;
    -webkit-transform: translateY(-20px);
    -moz-transform: translateY(-20px);
    -o-transform: translateY(-20px);
    -ms-transform: translateY(-20px);
    transform: translateY(-20px);
}
label {
    color: #bbb;
}

.float-labels input:focus {
  border-color: #ccc;
  box-shadow: none;
}
.float-labels input:focus + label, 
.float-labels input:invalid + label  {
  color: rgba(248, 151, 29, 0.77);
  -webkit-transform: translateY(-20px);
  -moz-transform: translateY(-20px);
  -o-transform: translateY(-20px);
  -ms-transform: translateY(-20px);
  transform: translateY(-20px);
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
  top: 14px;
  background: #211E1E;
}

Visit this codepen link for implementation details.

Answer №1

Similar to Detecting if an input contains text using CSS -- while I am on a website I cannot control?.

Check out this solution in your pen, especially if you are interested in using the "invalid hack" :)

 <input type="text" class="form-control input-lg" required>

Pair it with:

.float-labels input:focus + label, .float-labels input:valid + label{'styling'}

and http://codepen.io/anon/pen/QygwLR?editors=110.

Answer №2

Follow these steps to achieve it. Make sure you add placeholder=" " and required attributes to your input fields.

body{
    display: flex;
    justify-content: center;
    align-items: center;
}
.input-gp {
    margin-top: 150px;
    position: relative;
    
}
.input-gp input {
    position: relative;
    
}
.input-gp label{
    position: absolute;
    left: 5px;
    bottom: 5px;
    transition: all .4s ease;
}
.input-gp input:placeholder-shown + label{
    left: 10px;
    bottom: 5px;
}
.input-gp input:focus + label,
.input-gp input + label{
    bottom: 30px;
    left: 10px;
}
<body>
 <div class="input-gp ">
<input  type="email" name="" id="email" placeholder=" "       required>
   <label class=" position-absolute" for="email"> Email</label>
  </div>
  
 </body>

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

Battle of Kingdoms API ajax

When attempting to access Clash of Clans API information in this script, the following error is encountered: Refused to execute script from 'https://api.clashofclans.com/v1/leagues?authorization=Bearer%20eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6Ij ...

What causes the temporary halt of context execution in the eventloop framework?

Presenting the code immediately: setTimeout(() => console.log("next macro")); /// next macro Promise.resolve().then(() => gen.next()) /// microtask inside, #2 const gen = (function*(){ console.log("Hello"); yield; /// #3 console.log("W ...

I'm stumped trying to understand why I keep getting this syntax error. Any thoughts on how to fix it?

Our team is currently working on creating a dynamic SELECT box with autocomplete functionality, inspired by the Standard Select found at this link: We encountered an issue where the SELECT box was not populating as expected. After further investigation, ...

What is the best way to break out of a function halfway through?

What are your thoughts on using nested if statements? $scope.addToCart = function () { if (flagA) { if (flagB) { if (flagC) { alert('nononono!'); return; } } } e ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...

Warning: The username index is not defined in the file C:xampphtdocsindex.php at line 4

Hey there, I just wanted to express my gratitude for taking the time to read this. It's all part of a college assignment (web server scripting unit p4) where I am working on setting up a simple login system. Unfortunately, I keep running into an error ...

Oops! It seems like there is an issue with reading the property 'filter' of an undefined object. Any ideas on how to resolve this error

Having an issue with a custom filter that is causing an error "ERROR TypeError: Cannot read property 'filter' of undefined". I need help fixing this as it's preventing anything from rendering on the page. Any suggestions on what changes I sh ...

Unable to convert the value "undefined" to an ObjectId (type string) in the "_id" path for the "Order" model

As someone who is new to Javascript and working on an e-commerce website, I am currently facing a challenge with displaying the order id on the return page. Each time I try to do so, I encounter an error message that reads Cast to ObjectId failed for val ...

Utilizing CSS to style text on a menu by applying a specific class to an unordered list element

Is there a method to use CSS to invoke a div id function that will highlight text when the mouse hovers over it? <ul class="sub-menu"> <li id="menu-item-1721" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1721">< ...

Modify the title attribute within a span tag in PHP using AJAX

I'm currently working with Zend Framework 2 and I have a requirement to translate a string in my index.html file, which displays a tool tip when hovering over a span tag. The challenge I face is that this value needs to change dynamically after perfor ...

The MongoDB oplog displays repetitive patterns at unpredictable intervals

My current focus is on utilizing MongoDB and the oplog has proven to be a crucial component of my application. However, I've noticed a recurring issue during development where the oplog contains duplicate records (changes) 3 or 4 times. In an attempt ...

Utilizing a dropdown feature in Bootstrap for creating X columns of lists instead of a traditional single list

Check out my Fiddle. Beneath Dropdown1 lies a single-column list of actions. I'm looking to expand this list across multiple columns, like 5 or the width of the page. I'm hoping there's a Bootstrap CSS class I can use for this, but I migh ...

Ensure that the inner div has a height of 100%

Can someone help me troubleshoot my HTML code? <div id="container"> <div id="left-container"> </div> <div id="right-container"> </div> </div> Although the container is set to 100% height, the #left_con ...

Sending image id as a parameter to a MySQL query in PHP using jQuery

Having trouble passing image ids to mysql queries. I've tried the following code but keep getting an Undefined index x error. I've checked multiple Stack Overflow answers without success. echo "<img src=http://localhost/ss/img/".$p['pat ...

Select the first item that is visible and chosen

Currently, I am working with a select list: <option ng-repeat="hour in Hours" value="{{hour.Value}}" ng-show="filterEvent($index)" ng-selected="hour.Value == EventDate || $first"> {{hour.Text}} </opti ...

Guide to setting a default child route in react-router and updating the URL as needed

Currently, I am utilizing react-router v3 and have a segment of my routing code as follows: ... <Route path='dashboard' component={Dashboard}> <Route path='overview' component={Overview}/> <Route path='scan&apo ...

The presence of element a within the element ul is not permitted in this particular scenario. Additional errors from this section will not be displayed

Having trouble with this code snippet: <nav role="navigation"> <div id="menuToggle"> <input type="checkbox"/> <span></span> <span></span> <span></span> ...

Error Encountered - Configuring Node.js Deployment on the Heroku Platform

"APPLICATION ERROR - Oops! Looks like something went wrong with the application and we couldn't load your page. Please give it another shot in a little while. If you are the app owner, make sure to review your logs for more information." Hey there - ...

Is there a difference in performance between using multiple inline scripts versus one combined inline script?

Comparing Multiple Inline Scripts to a Single Conjoined Inline Script: <script type="text/javascript">/* some codeblock 1 */</script> <script type="text/javascript">/* some codeblock 2 */</script> <script type="text/javascript"& ...

The dynamic duo: Formik meets Material-UI

Trying to implement Formik with Material-UI text field in the following code: import TextField from '@material-ui/core/TextField'; import { Field, FieldProps, Form, Formik, FormikErrors, FormikProps } from 'formik'; import ...