Sliding Label with jQuery

Sliding Label with jQuery

I was using Sliding Label mooTools version for a while but when I had alot of jQuery scripts running up in one of my pages; it wasn’t that smart to include another library too.. obviously because it’s resource-consuming; so I wrote this small version for jQuery.

What is Sliding Label? an effect on input fields where the label slides out of it when the input gets the focus.. not clear enough? here is an example:

It’s a nice effect actually and I use it often.

The code:

$(document).ready(function ()
{
    var labelColor = '#999',
        restingPosition = 85;

    $("form#login_form .slider label").each(function ()
    {
        var label = $(this);
        var input = label.next("input");

        label.css(
        {
            'color': labelColor,
            'position': 'absolute',
            'top': 7,
            'left': restingPosition,
            'display': 'inline',
            'z-index': 1
        });

        var width = label.width();
        var move = restingPosition;

        if (input.val() !== '')
        {
            label.animate(
            {
                "left": "-=" + move + "px"
            }, "slow");
        }

        input.bind(
        {
            focus: function ()
            {
                if (input.val() == '')
                {
                    label.animate(
                    {
                        'left': '-=' + move + "px"
                    }, 'normal');
                    label.css(
                    {
                        'color': '#000'
                    });
                }
            },
            blur: function ()
            {
                if (input.val() == '')
                {
                    label.animate(
                    {
                        'left': '+=' + restingPosition + "px"
                    }, 'normal');
                    label.css(
                    {
                        'color': labelColor
                    });
                }
            }
        });
    });
});
Here is a complete example.

Enjoy, and stay tuned for more jQuery codes🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: