Creating a link swipe effect with Javascript

I saw this in last month’s .Net mag­a­zine and thought it was pret­ty cool and worth­while shar­ing.

With­out giv­ing away too much of the intri­ca­cies (see­ing as this is not my own work), this tech­nique essen­tial­ly boils down to using Javascript to append a <span> ele­ment to mask over each of the links on the hov­er event. The <span> ele­ments are set with 0 width ini­tial­ly, on the hov­er event, an ani­ma­tion is played to change the width to match that of the <a> ele­ments they’re mask­ing, a reverse ani­ma­tion is played when mouse moves out of the <a> ele­ments.

The HTML for the page is sim­ple enough:

<div id="wrapper">
<h1>Link swipe Demo</h1>
            <li><a href="#">Home</a></li>
            <li><a href="#">Previous</a></li>
            <li><a href="#">Next</a></li>

Some sim­ple CSS is used to style the links and the <span> ele­ments but the main thing is real­ly is this linkswipe func­tion which is called once the doc­u­ment fin­ish­es load­ing, I’ve filled in some more com­ments so hope­ful­ly it should be fair­ly self-explana­to­ry:

function linkswipe() {
    $("li a").each(function (i) {
        // keep a reference to the current <a> element
        var a = $(this);

        // get the title of the link
        var title = a.html();

        // get the width of the element
        var aWidth = a.outerWidth();

        // add a span with the title of the link to mask over the link for the hover event
        // set its initial width and display so that it's invisible
        a.append("<span class='mask' style='width: 0; display: none;'>" + title + "</span>");

        // keep a reference to the new span element
        var span = a.find("span");

        // add the hover event handler
        a.hover(function () {
            // stop any ongoing animation to stop the animation from flickering

            // expand the width of the span to completely cover the <a> element
            // when the mouse moves over
                width: aWidth + "px"
            }, 200);
        }, function () {
            // do a fade off animation when mouse moves off
                width: "0px"
            }, 400, function () {
                span.hide(); // hide the span once the fade animation completes

Here’s a quick demo of the effect, just hov­er over the links to see it in action: