Doesn't seem like jQuery's .blur() is responsive on dynamically created fields

I am currently designing a login form that includes a registration form as well. Using jQuery, the email field is generated dynamically.

The labels are positioned below the fields so that they can be placed inside the field. As the field gains focus or has content in it, the label moves above the field.

However, this functionality seems to work fine for the username and password fields but not for the email field. The reason behind this issue is unknown.

For reference, here's the link to the codepen:

http://codepen.io/andornagy/pen/waoyZB

$(document).ready(function(){

    var inp = $('#emailhere');
    var i = 0;
    var emailField = $('<section class="emailc"><input type="email" name="email" id="email" class="field"><label for="email" class="email">E-mail</label></section');

    // Do stuff when you click to show register form
    $('ul.tabs li.register').click(function(){

        $('#do').val('register');

        $('.button').val('Register');

        if ( i < 1 ) {

            $('#emailhere').after(emailField);

        };

    });

    // Do stuff when you click to show login form
    $('ul.tabs li.login').click(function(){

        $('.emailc').remove();

        var i = 0;

        $('#do').val('login');

        $('.button').val('Login');

    }); 

    // Moving the input labels correctly.
    $('#login').on("blur", "input",function() {

        // Make the label stay above if the field is not empty.
        if( this.value ) {
            $(this).next().addClass('notEmpty');
        }

        // Make the label go back on the field if the field is empty.
        if( !this.value ) {
            $(this).next().removeClass('notEmpty');
        }

    });

});
@import url(http://fonts.googleapis.com/css?family=Roboto+Slab);

body {
    margin: 0;
    padding: 0;
    background-color: #4A5043;
    font-family: 'Roboto Slab', serif;
}

.clear:after {
    display: block;
    content:" ";
    clear: both;
}

/* The Base container styles
===================================*/

.tabs {
    display: block;
    margin: -25px -25px 40px -25px;
    padding: 0;
    border-bottom: 3px solid #FFFFFF;
}

.tabs li {
    display: block;
    list-style: none;
    float: left;
    width: 125px;
    margin: 0;
    padding: 15px 25px 19px 25px;
    font-size: 22px;
    color: #FFFFFF;
    text-align: center;
}

.tabs .login {
    border-right: 1px solid #FFFFF;
}

#form {
    width: 300px;
    margin: 150px auto;
    background-color: #5C505A;
    padding: 25px;
}

#form .field {
    display: block;
    padding: 10px;
    font-size: 22px;
    margin-top: 14px;
    border: 3px solid #FFFFFF;
}

#form .button:focus,
#form .field:focus {
    outline: none;
    border-color:; #000000;
}

#form .field + label {
    position: relative;
    bottom:42px;
    padding: 10px;
    font-size: 22px;
    color: #5C505A;
    z-index: 999;
}

#form .field + .notEmpty,
#form .field:focus + label {
    bottom: 88px;
    color: #FFFFFF;
}

#form label:focus + label {
    bottom: 0;
    color: #5C505A;
}

#form .button,
#form .button:hover,
#form .field + label,
#form .field:focus + label {
    transition: 0.5s bottom,
                0.5s color,
                0.5s border-color,
                0.5s background-color;
}

#form .button {
    display: block;
    width: 294px;
    padding: 10px;
    font-size: 22px;
    border: 3px solid #FFFFFF;
    background:none;
    color: #FFFFFF;
}

#form .button:hover {
    color: #5C505A;
    background:#FFFFFF;
}
<!-- #form container -->
<section id="form">

    <ul class="tabs clear">
        <li class="login">Login</li>
        <li class="register">Register</li>
    </ul>
    <!-- #login container -->
    <section id="login">

        <!-- Login form -->
        <form name="login" action="#">

            <!-- Username field -->
            <p>
            <input type="text" name="username" id="username" class="field">
            <label for="username">Username</label>
</p>
            <div id="emailhere"></div>

            <!-- Password field -->
            <input type="password" name="password"id="password" class="field">
            <label for="password">Password</label>

            <!-- hidden value for validation -->
            <input type="hidden" id="do" name="do" value="login">       

            <!-- submit button -->
            <input type="submit" class="button" name="submit" value="Login">

        </form><!-- /ends Login form -->

    </section><!-- #login ends -->

    <!-- #register container -->
    <section id="register">

    </section><!-- #register ends -->

</section><!-- #form ends -->

Answer №1

After reviewing your code, consider trying this approach...

$('#login').on("blur", "input", function() {

...instead of using...

$('#login input').blur(function() {

The issue you are encountering is likely due to the dynamic field not being present at the time your code initializes the blur event. By using #login, the input can be located when it is added dynamically.

By utilizing the on method, it applies the event handler to #login, which is static, and then targets any input elements regardless of when they were created. Essentially, it functions similar to jQuery's find method for locating input elements.

This way, your code is effectively "attached" to #login while monitoring all input tags, whether they existed prior or were added later on.

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

Building a custom dialog box using Angular Material with HTML and CSS

I've been exploring different approaches to create a customized angular material dialog with a unique header using CSS/SCSS and the TailwindCSS framework. I am aiming for a specific visual effect, similar to what is shown in the figure below. desired ...

What is the most efficient way to apply multiple values to the css property outline?

Currently, I am working with IE11 to display a dialog box. The default style for the button in focus includes a dotted border. Is there a way to add an additional value for the outline attribute, like shown below: input[type=button]:focus{ outline: 1p ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

What is the best way to incorporate a confirmation model prior to accessing a dynamically generated link within a Jinja2 template?

I need assistance with deleting a record from an HTML table created within a Jinja2 template. I want to implement a confirmation prompt before proceeding with the deletion process. My development environment includes Bootstrap5. The current functionality ...

Preserving reference equality while passing props in React

Consider a scenario where a function dynamically generates some props for a component, and you want to pass all of them without specifying each individual prop that the function might generate. Typically, this can be achieved using the spread operator. How ...

Using CSS to design a table-like structure with rows that span multiple columns

I am trying to generate a table dynamically using CSS and a JSON array. For example: In the code snippet provided, I have assigned a class of 'spannedrow' to span certain cells in the table, although the class is not defined yet. This is just ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

Is your Node.js HTTP Request failing to function properly?

I am currently working on creating an HTTP Request function where all requests are directed to the same domain but with different file names. Unfortunately, I am encountering a problem where nothing is being displayed in the console and no data is being r ...

Using the symbols '&', '>', and '*' in the styling of React components

Below is the code snippet in question: const useStyles = makeStyles(theme => ({ row: { '& > *': { fontSize: 12, fontWeight: 'bold', color: 'rgba(33,34,34,0.5)', letterSpacing: 0.5, ...

I am wondering why the vue-router is only changing the URL and not displaying the corresponding view component

I've encountered an issue where the vue-router is only toggling the URL when clicking on the navigation link, but not updating the view component. Surprisingly, there are no apparent errors in my code. Despite this, the console indicates that the Home ...

Identifying Touch Interaction exclusively on WebGL Canvas within threejs

Currently, I am developing a threejs application that requires input from HTML buttons and utilizes Raycast Detection on touch within threeJS. The issue I am encountering is that when the user clicks an HTML button, the Raycast function is triggered as we ...

Using the HTML Style Tag in Android Development

After doing some research on articles and websites, I discovered that it is possible to create an HTML file and then display it using Android WebView. I referenced the following: Android WebView (WebKit) Tutorial Understanding User Interface in Android ...

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Using AngularJS to show/hide elements within a colgroup tag

Looking to create a dynamic table allowing users to hide certain columns. Wondering if it's possible to use ng-show with colgroup or col tags instead of adding ngshow to each cell individually. Struggling to make it work... <colgroup ng-repeat="mt ...

Having trouble submitting the form in ExpressJS - error encountered

Currently, I am in the process of learning ExpressJS and I have encountered an issue while trying to implement the login functionality. Whenever I attempt to submit the form using the POST method, I receive the following error message: "Cannot POST /login" ...

Unable to achieve text centering within a button using HTML and CSS

I'm diving into the world of HTML/CSS for the first time and encountering some issues along the way. In my setup.html, I created a "Continue" button and applied a class to style it in styles.css. However, I'm facing an issue where text-align cen ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

Using JSON to insert an array into an object with identical key name

var arr = ['1', '2', '3'] var part = {} var partContents = [] arr.map(function(i){ partContents.push({ obj: i }) part['text'] = partContents }) console.log(part); Is there a way to create separate arrays with ...

Looking to retrieve the checkbox value from HTML in AngularJS and pass it to the controller

How can I retrieve the value of a checkbox on button submit in a controller Function? <input id="Check" type="checkbox" ng-model="CheckValue" /> ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...