Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade In and Fade Out text inside a div

I have a div with a CSS style to show it as a button:

<div id="Word1" class="btn green" onclick="WordClicked(1);">Word 1</div>

And CSS styles:

.btn {
    display: inline-block;
    background: url(btn.bg.png) repeat-x 0px 0px;
    padding: 5px 10px 6px 10px;
    font-weight: bold;
    text-shadow: 1px 1px 1px rgba(255,255,255,0.5);
    text-align: center;
    border: 1px solid rgba(0,0,0,0.4);
    -moz-border-radius: 5px;
    -moz-box-shadow: 0px 0px 2px rgba(0,0,0,0.5);
    -webkit-border-radius: 5px;
    -webkit-box-shadow: 0px 0px 2px rgba(0,0,0,0.5);
}

.green      {background-color: #CCCCCC; color: #141414;}

I want to fade out text inside div, change text, and then fade in text again. But I don't want to fade in and fade out div.

If I use this javascript code:

$('#Word1').fadeOut('fast');

I will fade out div and text inside.

How can I do that?

like image 919
VansFannel Avatar asked Jun 07 '11 18:06

VansFannel


1 Answers

You want to wrap the text in a span then fade that out:

<div class="button"><span>TEXT!</span></div>

and you don't want to use fadeOut because that will change the size of your button as the text will disappear once fadeOut ends and no longer take up space. Instead animate the opacity:

$(".button").click(function(){
    $(this).find("span").animate({opacity:0},function(){
        $(this).text("new text")
            .animate({opacity:1});  
    })
});

http://jsfiddle.net/8Dtr6/

EDIT: Slight correction, as long as you immediately fade back in it does not seem to be an issue to use fadeIn and fadeOut, at least in chrome. I would expect maybe in lesser browsers to see a slight flicker, but could be wrong.

Possibly a bit cleaner using queue to avoid callbacks:

$(".button").click(function(){
    $(this).find("span")
        .animate({opacity:0})
        .queue(function(){
             $(this).text("new text")
                    .dequeue()
        })
        .animate({opacity:1});  
});

http://jsfiddle.net/8Dtr6/2

like image 52
James Montagne Avatar answered Oct 19 '22 10:10

James Montagne