Kid Diamond
Kid Diamond

Reputation: 2301

JQuery.css("display", "block") still ends up inline

When I check how this piece of code below affect my html live, I see that the span#error is faded out and faded in with display: block but changes right-after to display: inline.

How can I prevent this from happening?

jQuery

$(function() {
    $("#credentials .wrapper button").click(function() {
        $("span#error").fadeOut(300);
        $("span#error").html('<b style="color: #ce1919;">(!)</b> TEST').fadeIn(300).css("display", "block");
    });
});

JsFiddle

Upvotes: 0

Views: 204

Answers (4)

Alex W
Alex W

Reputation: 38223

I wouldn't even use fadeIn I would just use .animate(), since the documentation for fadeIn says that it just animates the opacity property, to prevent jQuery from messing with the display property at all:

$(function() {
    $("button").click(function() {
        $("span#error").fadeOut(300).stop();
        $("span#error").stop().html('<b style="color: #ce1919;">(!)</b> TEST').css({'opacity':'0','display':'block'}).animate({opacity:1},1000,function(){});
    });
});

http://jsfiddle.net/yfC2B/3/

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

When using fade in, the element will be displayed as his original state. Since you original state is none, jQuery will select the default display value of the element, which is in this case inline.

In you CSS, if you change the display value to block and hide the element in a DOM ready handle, everything work fine :

$(function() {
    document.getElementById('error').style.display = 'none';
    $("button").click(function() {
        $("span#error").fadeOut(300);
        $("span#error").html('<b style="color: #ce1919;">(!)</b> TEST').fadeIn(300).css("display", "block");
    });
});

http://jsfiddle.net/yfC2B/2/


I'm aware that using block element would be better, I am just telling why it doesnt not currently work.

Upvotes: 0

adeneo
adeneo

Reputation: 318252

jQuery's fading methods automagically sets the display type that the element has by default.

If you're going to set it to something else, do it after the fading has completed, or use a method that doesn't set the display property, such as fadeTo or animate()

$(function() {
    $("#credentials .wrapper button").click(function() {
        $("#error").fadeOut(300, function() {
            $(this).html('<b style="color: #ce1919;">(!)</b> TEST')
                   .fadeIn(300, function() {
                       $(this).css("display", "block");
            });
        });
    });
});

The real answer would be to just use a block element

<div id='error'>Error</div>

FIDDLE

Upvotes: 5

t.animal
t.animal

Reputation: 3331

This occurs because the fadeIn-method sets the display variable after fading in. Use the complete callback of the fadeIn-method to set the display-property of the span to block.

Upvotes: 0

Related Questions