Tobiq Tobiq - 1 year ago 94
CSS Question

Display Block Vs. Opacity

I have an on-hover menu which has to have

while it's not in use, so you can click things under it.

When it time to open it up, I turn the display to inline-block; and then fade in the opacity using css transition - with this code:

elm.onmouseover = function(){ = "inline-block"; = 1;

When this code does run, the element pops straight in without any fade.

My theory was that the javascript runs so fast that the element hasn't changed display type by the time the opacity change kicks in, so I did this:

elm.onmouseover = function(){ = "inline-block";
for (var i=1000...; i--; ); = 1;

It now visibly waits; however, still pops in without a fade.

I went into my console and ran: = "inline-block"; = 1; // run
> return message

and it didnt work; however, when I split the statements into two like this = "inline-block"; // run
> return message = 1; // run
> return message

It works fine, and the delay between the two is much less than the one caused by the for loop.

What is the root of this behaviour? I'm baffled.

Answer Source

DOM only refreshes once your entire code finishes, because it's sync with main-thread.

If you just wait a 1ms with a setTimeout, what you're expecting, will work:

elm.onmouseover = function () { = 'inline-block';
   setTimeout(function () { = 1;
   }, 1);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download