Search code examples
javascriptvisibilityopacity

how to force the browser to hide an element even if it is shown again after few seconds


Look at the following html code of the web page:

<!DOCTYPE html>
<html><head><script>
function hide()
{
 var e = document.getElementById('test');
 e.style.transition = 'visibility 0s,opacity 0s';
 e.style.visibility = 'hidden';
 e.style.opacity = '0';
 e.style.transition = 'visibility 5s,opacity 5s';
 show();
}
function show()
{
 var e = document.getElementById('test');
 e.style.visibility = 'visible';
 e.style.opacity = '1';
}
</script></head><body>
<div id="test">Test</div>
<button type="button" onclick="hide()">go!</button>
</body></html>

If you open this html file in any standard browser (I tested in on Mozilla Firefox and Opera, under Windows 7) and click the button, nothing will happen (the text 'Test' will not vanish!).

I'm guessing that this is a matter of a kind of 'intelligence' of the browser. So, my question is: is it possible (for the above html code) to force the browser to hide the element?


Solution

  • You should not perform multiple changes to the same style property at once (transition and opacity in your case), as only the last values assigned to those properties will actually get an effect. The other value(s) are not processed by the browser -- that only happens when you give control back to the browser.

    So only set the opacity to one value, the transition to one value, and then give control back.

    Use setTimeout for this: it gives control back to the browser who will call you back when a certain time has elapsed.

    function hide() { 
        var e = document.getElementById('test'); 
        e.style.transition = 'opacity 0s'; 
        e.style.opacity = 0; 
        setTimeout(showSlowly, 100); // This gives the browser time to perform the hiding action
    } 
    
    function showSlowly() {
        var e = document.getElementById('test'); 
        e.style.transition = 'opacity 2s'; 
        e.style.opacity = 1; 
    }
    <div id="test">Test</div>
    <button type="button" onclick="hide()">go!</button>