views:

76

answers:

2

Hey folks,

I'm just getting my bearings with Javascript and jQuery, and I'm working on an animation.

Essentially, what's going on is an element, #left-arrow. On hover, the arrow moves left 10px and increases opacity. I'm using the 2D Transform plugin for jQuery to handle the transform.

Now my issue, however, is that javascript will only execute it one at a time. So the arrow will move, THEN increase the opacity. The effect is sort of lost when it occurs this way.

Is there anyway I can combine these to work properly?

Here's what I have:

<script>
    jQuery(document).ready(
        function() {
            $('#left-arrow').hover(
                function() {
                    $(this).animate({translateX:-10})
                    $(this).fadeTo('fast', 1);

                },
                function() {
                    $(this).animate({translateX:0});
                    $(this).fadeTo('fast', .8);
                }
            )
    })
    </script>

As I said, I'm quite new at this, so please be specific if you have a solution, I really appreciate it!

+6  A: 

If you add opacity to your call to animate(), it'll animate that property at the same time as your translateX property. For example:

jQuery(document).ready(function() {
    $('#left-arrow').hover(
        function() {
            $(this).animate({translateX:-10, opacity: 1});
        },
        function() {
            $(this).animate({translateX:0, opacity: 0});
        }
    );

    $('#right-arrow').hover(
        function() {
            $(this).animate({translateX:10, opacity: 1});
        },
        function() {
            $(this).animate({translateX:0, opacity: 0});
        }
    );
});

I've combined your two calls to document.ready() into a single call, too.

EDIT: Also, if you're just moving your elements left and right and not doing any crazy rotation/scaling/etc., you can get away with making the element's position relative and just animating the 'left' property.

Faisal
Thanks, this works like a charm! left:; seems to work fine for what I need.
Judson Collier
+1  A: 

Hiya!

If for some reason you didn't want to combine the two effects as Faisal mentioned, the jQuery docs talk about simultaneous animations at http://docs.jquery.com/Release:jQuery_1.2/Effects#Simultaneous_Animations. You can pass animate() a queue: false flag in its options array. So:

jQuery(document).ready(function() {
        $("#left-arrow").hover(function() {
                $(this).animate({translateX:10}, {queue: false}).animate({opacity: 1}, {queue: false});
            }, function() {
                $(this).animate({translateX:0}, {queue: false}).animate({opacity:0}, {queue: false});
            }
        )
    }
}

Hope this helps.

Bacon