Change CSS when scrolling the page

Asked

Viewed 3,417 times

1

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

An example of a site that uses this is Deviantart.

That menu of TODAY BROWSEWHAT’S HOTUNDISCOVEREDDAILY DEVIATIONS suddenly gets fixed after the page undergoes a scrolling.

Can anyone give me an example of how to reproduce this to use on my websites?


NOTE: I unfortunately don’t know if this is CSS or Javascript, if possible, someone can correct my question.

2 answers

5


You can do it using a if/else together with the scrollTop() jQuery, as in the example of this code 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>

<div class="container">
    <div class="randomClass"></div>
</div>

0

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

  • Diego can complete the answer with an example?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.