Archive for jQuery

Sliding Label with jQuery

Posted in JavaScript with tags , , , on October 26, 2010 by Xacker

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 🙂