Rob
Rob

Reputation: 33

jQuery taking too long to render animation over large list of items

On my current project I have a table containing rows of items. Each item has a hidden checkbox over which an animation is executed as shown:

$('.elemToShow').each(function(){
    $(this).show('fast');
});

The problem is that as the list of items gets bigger, the function takes so much time to render that it simply "pops" on the screen after a while, instead of showing the animation as expected.

Is there any way to execute this function so that it animates regardless of the list size?

Upvotes: 2

Views: 609

Answers (3)

Gustavo Borges Michel
Gustavo Borges Michel

Reputation: 56

I think this may work.

Javascript:

function showCheckbox(element, elementClass, parentClass) {
    var $element = element;

    $element.show(200, function() {
        var $next = $(this).closest(parentClass).find(elementClass+':hidden').first();

        if ($next[0]) {
            showCheckbox($next, elementClass, parentClass);
        }
    })
}

showCheckbox($('.element:first'), '.element', 'tr');

Here is the HTML

<table>
<tr>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
    <td>
        <input type="checkbox" class="element" />
    </td>
</tr>

CSS:

.element {display:none}

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

If it's not the end of the world if older browsers don't support it, try this CSS:

.elemToShow {
    animation: fadein 0.5s ease;
}
@keyframes fadein {from{opacity:0} to{opacity:1}}

Remove the jQuery fade-in. By having the browser handle fading, it should be a lot smoother.

(Note that Chrome still uses the -webkit-animation and @-webkit-keyframes prefixed versions, but that will change next version)

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56439

No need for the overhead of the loop here, jQuery will already perform an each based on that selector. Try this:

$('.elemToShow').show('fast');

Upvotes: 4

Related Questions