Browser's repainting is very slow when using jquery addClass and removeClass

I have a page where I need to dynamically add or css classes. I have the following Jquery code in my page,

myElementsList.addClass('AClass').removeClass('BClass')

These css classes will change the color and background color of my elements. The problem is that this takes 2 or 3 seconds to repaint the browser.

If i use css classes which does not eXist(or does not repaint the browser) then it will eecute very quickly.

myElementsList.addClass('NotEXistClassA').removeClass('NotEXistClassB')

Any suggestion will be welcome?

Edit:

The way I solve this issue by changing the first 20 rows first and changing the remaining using a timer. I am also reseting this timer every time if the events raised again before the timer elapased.

Any other suggestion is welcome.

Upvotes: 2

Views: 3708

Answers (2)

Spudley
Spudley

Reputation: 168695

The problem here is that you are trying to get the browser to do two things at once, which both require it to repaint the same things.

But in fact you can achieve what you want to do (change the colour of the rows) by only doing one of the two actions.

The basic change you need to make is not to have a style for "not-selected" and another style for "selected", but instead to have one for "default" and one for "selected".

Then you can have the "default" style to set the standard colour, and simply add the "selected" style to override it; you don't need to remove the default style, as the selected one will override it.

Here's a simple bit of CSS to get you started:

.grid tr {
    background: #FFFFFF;  /*default white background*/
}

.grid tr.selected {
    background: #222222;
}

...and the script would just do addClass('selected') when you select it, and removeClass('selected') when you deselect it.

There really is no need for a not-selected class at all.

That simple change will remove a full half of the work that your program is doing when you toggle the selection, and in fact it will quite possibly speed it up by more an 50% due to it not having to do multiple re-paints on the same elements.

That will certainly get you going a bit faster. It isn't the whole story as to why your page is slow, but it will certainly help a lot.

Upvotes: 3

Bhanu Bais
Bhanu Bais

Reputation: 1

First remove class then assign new class

myElementsList.removeClass('BClass').addClass('AClass');

I think this may help you.

Upvotes: 0

Related Questions