Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.fadeOut() inside a hidden element - possible bug?

Tags:

html

jquery

css

Given the following code:

<div class='hotel_photo_select'>
    Hello
</div>

<div class='itsHidden' style='display:none'>
    <div class='hotel_photo_select'>
        Hello
    </div>
</div>

And:

$('.hotel_photo_select').fadeOut(300);
$('.itsHidden').show();

I would expect both .hotel_photo_select divs to be hidden. However, the second one is not hidden when I show the container.

Is this a jQuery bug? Every element should become hidden after fadeOut().

The only solution I think will be this :

$('.hotel_photo_select').fadeOut(300, function () {
    $(this).hide();
});
$('.itsHidden').show();

Which I find to be less than elegant.

like image 496
markzzz Avatar asked Aug 26 '11 09:08

markzzz


5 Answers

As "Boo" already mentioned, because the current state of second "hello" div is "hidden" jQuery.fadeOut() won't apply any animation on it.

Instead of saying "fade it out for me", you need to say "animate the opacity to 0". In this case jQuery won't care if your element is visible or not. it will do it's job:

$('.hotel_photo_select').animate({opacity:0}, 3000);

see it here: http://jsfiddle.net/QMSzg/20/

like image 71
Mo Valipour Avatar answered Nov 10 '22 00:11

Mo Valipour


Technically, for this type of method you need to use '.each()'. Then also lets add a checkpoint, where we determine if the parent is visible, if its not visible, then we make it visible.

However, making the parent visible, could have a negative effect on your layout, YES. But there is no better way to do this, and therefore you should avoid these types of situations.

Live example: http://jsfiddle.net/QMSzg/21/

$('.hotel_photo_select').each(function () {
    var this_parent = $(this).parent('div');
    if (this_parent.is(':hidden')) {
        this_parent.show();
    }
    $(this).fadeOut(500);
});
like image 28
BeatShot Avatar answered Nov 10 '22 00:11

BeatShot


jQuery.fadeOut transforms elements from their current state to the state you want to adopt, in this case hidden. If the element is already hidden (as with the second occurence), jQuery don't need to perform any action. What you could do is specifically set the css display to none:

$('.itsHidden .hotel_photo_select').css('display','none');
like image 42
Sgoettschkes Avatar answered Nov 09 '22 22:11

Sgoettschkes


place the show() before the fadeout()

$('.itsHidden').show();
$('.hotel_photo_select').fadeOut(300);
like image 38
Aleksandar Trajkov Avatar answered Nov 09 '22 22:11

Aleksandar Trajkov


I had the same problem. My solution was to hide the element as a call back function:

$('.hotel_photo_select').fadeOut(300, function(){
    $('.hotel_photo_select').hide();
});

This way if the element is hidden, the call back will be called right away.

like image 40
Tomer Almog Avatar answered Nov 09 '22 23:11

Tomer Almog