Search code examples
jqueryjquery-effects

Getting rid of a delay in fading in an item


If you see this JSFiddle here, I'm simply trying to animate in a button/link, albeit in a certain way. I want the link to still apply in layout so that the layout doesn't change at all.

My HTML:

<p>
    <a id="helloWorld" href="#" class="btn primary large">Hello, World! &raquo;</a>
    Fork this to get hacking on <span class="label stark">Bootstrap</span> and <span class="label stark">jQuery</span>.
</p>

My CSS:

#helloWorld { 
     visibility: hidden;
} 

My jQuery:

$("#helloWorld")
    .delay(1000) // after a second
    .css("visibility", "visible") // make it 'visible
    .hide() // but hide it 
    .fadeIn(500); // then fade it in

I have to do the visibility:visible then hide() hack as noted here. The weird thing is that if I disable my JavaScript altogether, the link takes up the space normally. If I enable the JavaScript, then the layout gets all messed up. It appears that for some reason, it's executing the css() and the hide() before the delay is over! What am I doing wrong?


Solution

  • The reason your code does not work is because .delay() does not work the same as javascript's setTimeout. Check out http://api.jquery.com/delay/ for more documentation on that.

    Try this fix:

    setTimeout(function() {
      $("#helloWorld").css("visibility", "visible").hide().fadeIn(500);
    }, 1000);
    

    Here is the jsfiddle: http://jsfiddle.net/7LGrS/2/