0

I am trying to make a floating label float when you click the input. I am using CSS and jquery(This is in a jquery mobile 1.4.4 platform). My code only seems to work on an input with a data-role of "none," and it won't work on a normal input. How can I make this work on a normal input?

This is my CSS:

    .inputAnimation {
  display: inline-block;
  position: relative;
  margin: 0 0px 0 0;
}


.inputAnimation label {
  position: absolute;
  top: 5px;
  left: 15px;
  font-size: 12px;
  color: #aaa;
  transition: .1s all linear;
  cursor: text;
}

.inputAnimation.active label {
  top: -15px;
}

This is my HTML:

<div data-role="page" id="signUpPage">
<div data-role="main" class="ui-content">
    <form>

        <div class="inputAnimation">
            <label for="username">Name</label>
            <input id="username" name="username" type="text" />
        </div>
        <div class="inputAnimation">
            <label for="email">Email</label>
            <input data-role="none" id="email" name="email" type="text" />
        </div>
    </form>
</div>

And this is my jquery

 $(document).ready(function () {

    $('input').each(function () {

        $(this).on('focus', function () {
            $(this).parent('.inputAnimation').addClass('active');
        });

        $(this).on('blur', function () {
            if ($(this).val().length == 0) {
                $(this).parent('.inputAnimation').removeClass('active');
            }
        });

        if ($(this).val() != '') $(this).parent('.inputAnimation').addClass('active');

    });
});

Here is the demo

Link to the jsfiddle

Thanks!

1 Answers1

0

When jQM enhances the input it adds a DIV such that .inputAnimation is now a grandparent of the input instead of parent. The simplest change is to use the .parents() instead of .parent() method:

$('input').each(function () {

    $(this).on('focus', function () {
        $(this).parents('.inputAnimation').addClass('active');
    });

    $(this).on('blur', function () {
        if ($(this).val().length == 0) {
            $(this).parents('.inputAnimation').removeClass('active');
        }
    });

    if ($(this).val() != '') $(this).parents('.inputAnimation').addClass('active');

});

Updated FIDDLE

ezanker
  • 24,628
  • 1
  • 20
  • 35