Chris Felstead
Chris Felstead

Reputation: 1208

jQuery animation - inconsistent after first run

I have a list of images that float alongside each other and some links to javascript calls at the top of the page. On clicking a link, all visible images should shrink and vanish and the selected items then expand out and become visible.

This works fine the first time. However, subsequent changes in the selection give unpredicatable results with the fading not always happening.

I've created a jsFiddle example which better shows the issue. Any help is great appreciated.

Chris.

Upvotes: 0

Views: 186

Answers (1)

glortho
glortho

Reputation: 13198

The problem is that animations are run on each element individually, as are the callbacks. So showList is running 15 times.

One way around this is to use a count to track when the last animation has run. For example:

function collapseList(selectedFilter) {
    var els = $('.listItem'),
        count = els.length;

    els.animate({
        opacity: 0,
        width: "0px",
        height: "0px"
    }, 2000, function() {
        if ( !--count ) {
          els.hide();
          showList(selectedFilter);
        }
    });
}

Try it here: http://jsfiddle.net/msb9p/11/

Upvotes: 1

Related Questions