Aske Lange
Aske Lange

Reputation: 38

Is adding css styling to a HTML element through vanilla JavaScript async?

fellow nerds, I recently stumbled across something rather strange, that essentially breaks the web app I'm working on... Which is that css attributes I add to an HTML element through (vanilla) javascript, seems to be async, to demonstrate that I have a small piece of code...

   ...

    _( leftView ).addClass('notrans');
    _( rightView ).addClass('notrans');

    if ( fromLeft ) {
        if ( !rightFocused ) {
            _( leftView ).css({ 'left' : '-100%' })
            _( rightView ).css({ 'left' : '-50%' });
        } else _( leftView ).css({ 'left' : '-50%' });
    }

    if ( fromRight ) {
        if ( !leftFocused ) {
            _( leftView ).css({ 'left' : '100%' });
            _( rightView ).css({ 'left' : '150%' });
        } else _( rightView ).css({ 'left' : '100%' });
    }

    _( leftView ).removeClass('notrans');
    _( rightView ).removeClass('notrans');

    ...

NOTE: The small underscore you see everywhere, is a small library I made and tested... And I'm 99% sure that the CSS, add class and remove class functions work.

Now, the problem is that when I get to the remove class part of the code ( last two lines ), the CSS doesn't seem to have been applied yet. So when it finally does, I will already have removed the notrans class, and the elements will move with a transition instead of none. This can be fixed with a 1ms timeout to the removal of the classes but will break some other stuff down the line... So is there anybody that knows if adding CSS attributes through JS is async, and how to fix it?:)

Aske K.

Upvotes: 1

Views: 114

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

Yes and no.

When you have JavaScript making changes to the CSS, the changes are queued and then all applied together when the JavaScript is done.

Exception: certain properties cause a recalculation to be done. For example, getting measurements like offsetHeight causes the browser to apply any pending CSS changes, make the measurement, then continue.

However, I don't know for sure if transitions are properly applied even if a measurement is done. The easy way would be to make the removeClass async, by sticking it in setTimeout(... , 1) or (better) requestAnimationFrame (which is called the very next frame, well after the CSS has updated)

Upvotes: 2

Related Questions