css won't transition after jquery fade out

37 Views Asked by At

Using css media query and opacity transition, I have a div that fades in when viewport is less than 640px, and it fades out when viewport is wider.

Using jquery, I also have a button that when clicked will fade out the div.

The problem i have is that after the click/jquery fade out, the div will no longer fade back in when the viewport is changed.

I'd like the div to be able to transition back and forth 100%-0% opacity via viewport change even after the user has clicked the button to fade it out.

css:

#myDiv {
            position: absolute; left: 0; top: 0; width: 100vw;
            opacity: 0;
            transition: opacity 1.5s;
        }
@media screen and (max-width: 640px) {
    #myDiv {
                position: absolute; left: 0; top: 0; width: 100vw;
                opacity: 1;
            }  
    }

html:

<div id="myDiv">
    <div id="closeBtn" onclick="xOut();">
    </div>
</div>

script

xOut = function() {
    $("#myDiv").fadeOut(2000);
    });
}

It seems to me that the jquery is breaking the css. I can't figure out how to fix this.

1

There are 1 best solutions below

2
VoidZA On

This is happening because the fadeOut function adds display:none; to the element after it faded out, which will cause issues with css transitions.

Basically what you want to do is to use a class that hides it without using display: none; You can also use styles like height: 0; pointer-events:none; to further remove it from view.

The below snippet shows how using a css class to fade it out compares to the fade out function. I am not sure if this is the functionality you are looking for, but it should help you understand what is going on.

xOut = function() {
    $("#myDiv").fadeOut(2000);
}

xOutCss = function() {
    $("#myDiv").addClass('faded');
}
#myDiv {
  transition: opacity 2s ease;
}
.faded {
  opacity: 0;
}

@media screen and (max-width: 640px) {
  #myDiv {
    position: absolute; 
    left: 0; 
    top: 0; 
    width: 100vw;
    opacity: 1;
  }
  #myDiv.faded {
    opacity: 1;
  }
  #fade_out_btn {
    display: none;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
  <button onClick="xOut();">Fade Out</button>
  <button id="fade_out_btn" onClick="xOutCss();">Fade Out Css</button>
</div>