twan
twan

Reputation: 2659

How can I animate or transition CSS when a class is added with jquery

I've tried multiple examples but for some reason my CSS just won't animate. CSS keyframes worked but I am adding and removing a class to resize a logo when scrolling down. With keyframes it resizes to a smaller logo when scrolling down, but jumps immediately back to big when scrolling back up again.

This is my code:

Logo html:

<div class="col-lg-3 col-md-2 col-sm-6 col-xs-5">
    <a class="logolink" href="#"><img src="asset/img/logo-white.png" alt=""></a>
</div>

My jQuery:

if ($(this).scrollTop() > 50) {
    $('.logolink img').addClass('logo-small');
} else {
    $('.logolink img').removeClass('logo-small');
}

And my CSS:

.logolink{
  position: relative;
  display: inline-block;
}

.logo-small{
  max-height:100px;
}

I've tried adding transition: height 2s; or transition: max-height 2s; to .logo-small but this doesn't work. What is the correct way to do this?

Upvotes: 0

Views: 97

Answers (1)

Ahmed Tag Amer
Ahmed Tag Amer

Reputation: 1422

Is this what you trying to do ?

$(document).on("scroll",function(){
if ($(this).scrollTop() > 50) {
    $('.logolink img').addClass('logo-small');
} else {
    $('.logolink img').removeClass('logo-small');
}
});
body{
  height:200vh;
}

.logolink{
  position: fixed;
  top:0;
}

.logolink img{
  height:300px;
  transition-duration:0.5s;
}

.logo-small{
  height:100px!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-2 col-sm-6 col-xs-5">
    <a class="logolink" href="#"><img src="https://picsum.photos/id/237/200/300" alt=""></a>
</div>

Upvotes: 1

Related Questions