Home > Software engineering >  Change Css if Oopacity is equal to 0
Change Css if Oopacity is equal to 0

Time:03-28

I have this content that I let disappear by clicking on a button. Since I want to make this with a smooth transition, I use opacity for that. But here is the problem:

The Content is on top of other content via z-index. If the content is hidden, I want to click on the Content that gets revealed. To hide the content I use the following code:

$('.close-button').click(function(e) {
      $('.hidden-content').css({
        "opacity":"0"
        });
    });

To solve my problem I just could change the z-index in the same function. But if I do that I lose my smooth transition of disappearing that content. So what I need is another code that is executed after the one above and changes the z-index only after the opacity is set smoothly to 0. For this I tried some if statements like the following:

var hide = $('.hidden-content').css('opacity');
if (hide == 0)
         $('.hidden-content').css({
        "z-index":"-1"
         });

and also:

$(function() {
    if ($('.hidden-content').css('opacity') == 0)
         $('.hidden-content').css({
        "z-index":"-1"
      });
});

Nothing seem to work. It seems like a small piece but it already cost me hours. That is why I created an account here and reach out for help since so many posts helped me in the past.

And before I forget to mention: I am quite new to all this so maybe there is a super easy solution (hopefully).

If you need any more information, please let me know. Thank you!

CodePudding user response:

If you're changing the opacity using a CSS animation, you can create a keyframe at the very end of the animation to change the z-index.

So if you have an animation that looks like this:

@keyframes opacityanimation {
   0% { opacity: 100; }
   100% { opacity: 0; }
}

You can modify it to change the z-index at the very end:

@keyframes opacityanimation {
   0% { opacity: 100; }
   99% { opacity: 0; }
   100% {
       opacity: 0;
       z-index: -1;
   }
}

Note that you have to set opacity to 0 at the very end as well.

CodePudding user response:

You can animate the opacity and then change the z-index, when the animation is complete:

$('.close-button').click(function(e) {

$('.hidden-content').animate({"opacity":"0"}, function(){
$(this).css({"zIndex":"-1"})
});

});
  • Related