pjgat09
pjgat09

Reputation: 133

Jquery: Hiding a div inside a hidden div with animation

I am trying to hide a <div> which is inside another <div> that is hidden. I am using an animation: $("#innerDiv").hide(400), but as long as the outer <div> is hidden the inner <div> doesn't get hidden and is later visible when I unhide the outer <div>. If the outer <div> is shown, the inner <div> gets hidden with an animation as expected.

I don't expect the inner <div> to hide with an animation when the outer <div> is hidden since that wouldn't make sense. I would however expect that the <div> would at least become hidden, which isn't the case.

I found that changing the javascript to $("#innerDiv").hide() fixes the problem, but removes the animation that I would like to be there for when the outer <div> is visible.

Here is a jsFiddle demonstrating the problem. If you click the "Show" button first, then click the "Hide" button, the text disappears with an animation as I expect it to. However if you click the "Hide" button first, then click the "Show" button the text still appears. I expect it to be hidden (since I used the .hide() function.).

Why is this happening, and is there a way to keep the animation for when the outer <div> is visible, but make the .hide(400) actually hide the element when the outer <div> is hidden?

Upvotes: 2

Views: 1030

Answers (2)

VulgarBinary
VulgarBinary

Reputation: 3589

You can write a snippet to toggle the animation depending on if the parent is hidden:

var innerDiv = $("#innerDiv");
if(innerDiv .parents("div").is(":visible")){
    innerDiv.hide(400);
}else{
    innerDiv.hide();
}

Edit: Explaining parents(...) selector further

You could also use the .parents("...") call with any selector. Thus if the nested div is deper than the immediate child it will still bubble up to find the targeted parent you want to check. So if your parent div is named id="outerDiv" you could do:

$("#innerDiv").parents("#outerDiv").is(":visible")

Edit: A more general workaround

You could also do this for any element to determine whether it is hidden (You could write your own custom plugin for animate or just hide, but I'll leave that to you)

$(function(){
     HideOrAnimate($("#whatever"),400);
});

function HideOrAnimate(target, hideTime)
{
     if(target.parents(":hidden").length > 0){
          target.hide();
     }else{
          target.hide(hideTime);
     }
}

Upvotes: 1

MJC
MJC

Reputation: 3939

You can use the callback option to manually change the inside div css display property to

display : none

hide documentation

Upvotes: 1

Related Questions