Nick Petrie
Nick Petrie

Reputation: 5598

How do I hide jQuery changes to the page until all processing is complete?

I have a page with a large table. At the top of the table I've added several filters for eliminating rows in the table. When someone changes a filter, jQuery processes the changes and shows/hides rows in the table that match the filters.

The processing code starts by showing all the rows in the table. Then, it steps through each filter, and wherever necessary, it hides rows in the table. So, each time the user changes a filter, they will see the entire table momentarily and then watch as the rows disappear until the filtering is complete.

Is there a JavaScript or jQuery function for delaying output to the browser until all processing is complete?

Upvotes: 3

Views: 196

Answers (3)

jfriend00
jfriend00

Reputation: 707298

I know you've already accepted an answer, but cloning the table is not how I would choose to implement this. I'd prefer to change the code that modifies the table to not modify it directly. Instead, create an output array that contains the list of modifications you will make to the actual visible table. Then, run your code and have it create this output array (which rows are shown and hidden or any other modifications). Then, when the lengthy part of the code is all done and you have this output array, you simply loop through the final output array and apply the changes. If this last part is all done in one synchronous piece of JS, the viewer will not see the intermediate steps, just the final result.

You should note that there are some characteristics of cloning and operating on it before it's inserted into the document to be aware of:

  1. There could be issues cloning and operating on something with ids assigned to elements in it (since you can only have one object with a given id).
  2. Non-jQuery event handlers may not get copied onto new objects.
  3. You should specify the appropriate parameters to the .clone([withDataAndEvents], [deepWithDataAndEvents]) function
  4. If your table is large, cloning might be slow (lots of duplicate objects and properties to create).
  5. If any of your operations to modify the table assume it's in the document, they might not work on the cloned table until it's inserted.

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

You can clone the table, perform whatever operations you need to on the clone, and replace the original table once you're done:

var newTable = $("#yourTable").clone();
//Do whatever you need to do to newTable
$("#yourTable").replaceWith(newTable);

Here's a working example.

Upvotes: 5

Joe
Joe

Reputation: 82594

Here is a crude example: http://jsfiddle.net/YNZJf/

Basically use jquery to change the html, then once finished set it back to you table.

$tmp = $( $('#table').html()));
$tmp.filter(); // do work;
$('#table').html($tmp.html());

Upvotes: 1

Related Questions