Search code examples
javascriptjquerycsssmooth-scrollingsmoothing

How to make image size change smoothly on scroll?


I have header with big logo i want to make it small after scroll more than 100px, this is working fine but not smoothly, how can i do it smooth?

My Code:-

$(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 100){
            $('header').addClass('fixed-header');
        }
        else{
            $('header').removeClass('fixed-header');
        }
    });
});
header{ padding:0px; position: sticky; top:0px; left:0px; background: #FFF; z-index: 1000;}
header.fixed-header{box-shadow: 20px 4px 10px rgba(39, 59, 69, 0.2);}

header .logo img{width:200px;}
header.fixed-header .logo img{width:100px;}

.box-height{ height:500px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<header>
    <div class="col-md-4">
      <a href="#" class="logo"><img src="https://www.freepnglogos.com/uploads/google-logo-png-hd-11.png"></a>
  </div>
</header>

<div class="box-height"></div>


Solution

  • Solution

    transition: all linear .5s
    

    Explanation

    You can take a look at the transition property in CSS.

    Taking into consideration the solution above, here's a break down of the syntax:

    1) transition-property: defines which property you want to animate. It can be a single property, multiple properties or all;
    2) transition-timing-function: transition function to be used, it will define how the animation will occurs;
    3) transition-delay: defines how long the animation will take to finish;

    References

    Using CSS transitions

    Example

    $(function(){
        $(window).scroll(function(){
            if($(this).scrollTop() > 100){
                $('header').addClass('fixed-header');
            }
            else{
                $('header').removeClass('fixed-header');
            }
        });
    });
    header{ padding:0px; position: sticky; top:0px; left:0px; background: #FFF; z-index: 1000;}
    header.fixed-header{box-shadow: 20px 4px 10px rgba(39, 59, 69, 0.2);}
    
    header .logo img{width:200px; transition: all linear .5s}
    header.fixed-header .logo img{width:100px;}
    
    .box-height{ height:500px;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <header>
        <div class="col-md-4">
          <a href="#" class="logo"><img src="https://www.freepnglogos.com/uploads/google-logo-png-hd-11.png"></a>
      </div>
    </header>
    
    <div class="box-height"></div>