Change CSS by scrolling the page

1

I was wondering how to swap a page's CSS after it gets scrolling out of its default location.

An example of a site that uses this is Deviantart.

This TODAY BROWSEWHAT'S HOTUNDISCOVEREDDAILY DEVIATIONS menu is suddenly fixed once the page has been scrolling.

Does anyone know how to reproduce this to use on my websites?


NOTE: I unfortunately do not know if this is CSS or Javascript, if it is possible, someone can correct my question.

    
asked by anonymous 30.08.2015 / 21:11

2 answers

5

You can do this using if/else along with scrollTop() of jQuery, as in the example below:

// O código abaixo deverá ser implementado dentro de uma tag <script> caso implementada no código HTML
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 50) {
    $('.randomClass')
      .css({
        'background-color': 'tomato',
        'position': 'fixed'
      });
  } else {
    $('.randomClass')
      .css({
        'background-color': 'burlywood',
        'position': 'inherit'
      });
  }
});
.container {
    height: 900px;
    position:relative;
}
.randomClass {
    height: 30px;
    width: 100%;
    background-color: burlywood;
}
<!-- A Biblioteca jQuery abaixo deve ser implementada dentro do <head> do seu site/aplicação -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><divclass="container">
    <div class="randomClass"></div>
</div>
    
30.08.2015 / 22:26
0

This is done via CSS, adds the property position: fixed; to the element.

    
30.12.2015 / 21:36