Search code examples
javascriptjqueryhtmlcsscss-position

How to animate to position fixed?


I try to animate a DIV that gets fixed after 1 second. But I can't make it done. I want after one second the div called "homepage-hero-module" to slide from right to left. As you can see in the FIDDLE it changes to fixed after one second. So How to animate this?

I tried with css, but no luck.

-webkit-transition: left 1s;
  -moz-transition: left 1s;
  -o-transition: left 1s;
  transition: left 1s;

and

-webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;

JSFIDDLE

HTML CODE:

<div class="container-fluid">
    <div class="homepage-hero-module">
        Container with data
    </div>
</div>

CSS CODE:

    body, html {
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
}
.container-fluid {
  width: 100%;
  height: 100%;
  position: relative;
}
.homepage-hero-module {
  background: #DDD;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
}
.fixed {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 20px;
    height: 100%;
    background: red;
}
img {
  height: 100%;
  width: auto;
}

JS code:

$(document).ready(function() {
    setTimeout( function(){
              $('.homepage-hero-module').addClass('fixed');
    },1000);
});    

Solution

  • You need to animate the width while position is still absolute, and then set the position to fixed

    <div class="container-fluid">
        <div class="homepage-hero-module">
            Container with data
        </div>
    </div>
    
    body, html {
      margin: 0px;
      padding: 0px;
      width: 100%;
      height: 100%;
    }
    .container-fluid {
      width: 100%;
      height: 100%;
      position: relative;
    }
    .homepage-hero-module {
      background: #DDD;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0px;
      left: 0px;
      transition:all .2s ease;
    }
    .fixed {
        top: 0px;
        left: 0px;
        width: 20px;
        height: 100%;
        background: red;
    }
    img {
      height: 100%;
      width: auto;
    }
    
    $(document).ready(function() {
      setTimeout( function(){
        $('.homepage-hero-module').addClass('fixed');
      },1000);
    
      $('.homepage-hero-module').css('position','fixed');
    });