Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery fadeIn() results in display: block for inline element

Tags:

jquery

css

http://jsfiddle.net/chovy/dk5Ua/

<div></div>

var $span = $('<span>foo</span>');

$span.hide();
$("div").append($span);
$span.fadeIn();

You'll notice the resulting span has inline style display: block; instead of inline.

This is the resulting html:

<span style="display: block;">foo</span>

How do I get the fadeIn() to result in display: inline?

like image 880
chovy Avatar asked Nov 08 '12 01:11

chovy


3 Answers

I just found a simple solution to a similar problem. In your case, the fix would be this:

$span.css('display', 'inline').hide().fadeIn();
like image 58
Shomz Avatar answered Sep 18 '22 06:09

Shomz


I'm with Adrian; that really wasn't a question. But you are correct: jQuery does a very naive translation of display properties when you use anything that show/hides elements (eg. show, hide, togle, fadeOut, etc.).

I've honestly never understood why they do this (it'd be much simpler to simply set display to:

isShown ? '' : 'none';

instead of their logic, which is essentially:

isShown ? 'block' : 'none';

) but they have reasons for just about everything they do, so I imagine they have a some logic behind setting the wrong display types on things.

* EDIT *

As I suspected, the jQuery people did have their reasons (see the comments from jfriend00); also I see that there's an actual question in the question now:

How do I get the fadeIn() to result in display: inline?

The answer is that you need to look at how fadeIn works; essentially it's just:

this.animate({opacity: "show"}, speed, easing, callback );

In other words, it's roughly equivalent to:

this.animate({opacity: '100%'}, speed, easing, function() {
    this.css('display', 'block')
});

(WARNING: I'm not actually a big user of jQuery's animation features, so while the above code should work, I make no promises).

Given that, if you want to set the display to something else (like say 'inline'), you can do:

this.animate({opacity: '100%'}, speed, easing, function() {
    this.css('display', 'inline') // or you could use this.css('display', '')
});
like image 41
machineghost Avatar answered Sep 18 '22 06:09

machineghost


I found this extremely useful, and somewhat simpler (based on MakuraYami's answer to this question):

$span.fadeIn().css('display', 'inline');
like image 33
Chris Kempen Avatar answered Sep 19 '22 06:09

Chris Kempen