jQuery workaround when addClass does not cause a UI repaint

By on

With jQuery you can easily add a css class to an element. For example, imagine the following button:

<button id="sign" class="btn-primary">Sign</button>

I wrote some nice code which makes the work a little bit more like native Android buttons. When somebody causes a touchstart event I would like to see the button become a darker look. My first approach was to add a class like this:

$('#sign').addClass('touched');

And finally remove it again when the touch ended:

$('#sign').removeClass('touched');

It should be straightforward, but while the CSS was OK and the addition of the class actually happened to the element, the UI element was not repainted by the mobile browser. It simply looked as nothing would have happened. As I found out, the browser does only repaint when the executing JavaScript thread has finished or makes a pause. Some people suggest to add a timeout to the thread to give the browser a chance to repaint. I don't like that approach. Why should I spent a lot of time in developing a button (!) when I finally add timeouts to make it work proper?

I tried a little bit and found out that removeClass is working as expected. This is also the case if somebody would add a style attribute. I didn't want to apply styles directly to the element, but it is very useful to know that removeClass would work. I inverted my logic. Instead of adding a class when touched, I plan to remove it.

My button changed too:

<button id="sign"
   class="btn-primary btn-primary-untouched">Sign</button>

The class btn-primary-untouched is defined later in the CSS as btn-primary and overwrites the background color. It is also brighter in color than btn-primary. When the touchevent starts I remove the "untouched" class and the button remains in darker color.

When the touchevent ends I add it back. At this time the javascript execution is already at end and so I do not need to care on the issue.

Currently this is tested with Android 4.x (emulator), Android 3.x. No idea on the iPhone, if somebody knows, feel free to comment.

Tags: CSS, JavaScript, jQuery, mobile