Bruno Carvalho
Bruno Carvalho

Reputation: 29

Remove class when page loads and add class when leaving the page

I'm trying to animate a div so it appears when I open the page and disappears when I leave the page. I was able to make it appear but not disappear. here's what I have:

.crvlh{
float: left;
width: 94vw;
overflow: hidden;
margin-top: 10vw;
opacity:1;
transition: opacity 1s ease-in-out, margin-top 0.5s ease-in-out;}

.crvlh.load{
opacity: 0;
margin-top: 13vw;   
transition: opacity 1s ease-in-out, margin-top 0.5s ease-in-out;}


$(window).load(function () {$('.crvlh').removeClass('load');});
$(window).unload(function () {$('.crvlh').addClass('load');});

Upvotes: 1

Views: 555

Answers (1)

rollstuhlfahrer
rollstuhlfahrer

Reputation: 4078

The unload event is fired, after the browser has already hidden the page. From MDN (emphasis mine):

The document is in a particular state:

  • All the resources still exist (img, iframe etc.)
  • Nothing is visible anymore to the end user

In order for the user to see the unloading animation, you need to trigger it earlier.

One way is to use the beforeunload event (MDN)

Upvotes: 3

Related Questions