Skip to content Skip to sidebar Skip to footer

Jquery- Dynamically Alternate Between Image Sources Within An Animated Div

I have a menu that is animated to slide across the page when triggered by clicking on an image of an arrow. I'd like to switch the arrow to a different image source once the menu's

Solution 1:

jQuery's .animate has a callback that is called when the animate is finished so you can use that to change the images at the appropriate time:

$(function() {
    $('#trigger_right').toggle(function () {
        $('#slider').animate({'width':'100%'}, 1500, function() {
            $('.arrow_small').attr('src','images/right_small.png');
        });
    }, function() {
        $('#slider').animate({'width':'30px'}, 1500, function() {
            $('.arrow_small').attr('src','images/left_small.png');
        });
    });
});

The above assumes that you only have one .arrow_small element of course. Using a class for the arrow and a sprite sheet for the images would be better but that would only require changing the $('.arrow_small').attr() parts to $('.arrow_small').toggleClass() calls as Rob suggests.

Solution 2:

If I understand correctly, you only want the images to change after the menu animation has completed.

One way, perhaps not the best, would be to make the JavaScript that changes the src attribute occur after a set period of time using setTimeout(). Instead of:

$('.arrow_small').attr('src','images/right_small.png');

You would have:

setTimeout("toggleImages()", 1500);

functiontoggleImages(){
    // some code to toggle them
}

I haven't tested this, but give it a try. Hope it helps!

Solution 3:

I would suggest you set the images up in CSS as classes and then do something like:

.toggleClass("right-small left-small");

Post a Comment for "Jquery- Dynamically Alternate Between Image Sources Within An Animated Div"