views:

85

answers:

3

I have a large set (around 100) of page elements that I would like to toggle (show/hide) with jQuery. I just use $(".toggleElementClass").toggle(); This looks like the trivial solution.

The problem is this takes a few seconds, even on the latest Chrome browser. Is there a faster, more efficient way to achieve the same effect.

+2  A: 

Its very hard to answer this correctly with the information provided. But one improvement which helps a lot in these scenarios is try to narrow down your DOM search context instead of using $(".toggleElementClass").toggle(); its better to use $("#myelements > .toggleElementClass").toggle(); will narrow down where jQuery looks up for the elements to toggle.

Teja Kantamneni
The order of efficiency in terms of searching the dom is: ID, tag, *then* class. So: `$("#ParentContainer > element.class").toggle();` might be a bit better.
Plan B
+6  A: 

You can reduce the amount of work the browser has to do by leveraging stylesheets to key all the display changes off a single attribute change — typically, the classname of an ancestor element. This means you can cause them all to change at once rather than one-by-one, reducing the number of reflows and improving speed. For example:

<style type="text/css">
    #mything p.toggled { display: none; }
    #mything.toggled p { display: none; }
    #mything.toggled p.toggled { display: block; }
</style>

<div id="mything">
    <p> foo </p>
    <p> bar </p>
    <p> bof </p>
    <p> zot </p>
</div>

<button id="toggle-all">all</button>

<script type="text/javascript">
    $('#mything>p').click(function() {
        $(this).toggleClass('toggled');
    });
    $('#toggle-all').click(function() {
        $('#mything').toggleClass('toggled');
    });
</script>
bobince
Short and efficient. Nice!
Ariel
Works!!! Thanks you
Ron Harlev
A: 

Just upgraded to jQuery 1.4.2 It made this all issue irrelevant. Even on a "slow" IE7 or IE8. It is just so much faster. Unbelievable.

Ron Harlev