Tutorials JavaScript Scrolling Sticky

Scrolling Sticky

This tutorial will show you how to create an element that will scroll with the browser after a certain amount of scrolling.

CSS

First of all, we need to make a class with a fixed position. A fixed position means that element will always scroll with the browser.

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

JavaScript

The above code works if you want that element to always scroll, but sometimes you want to stick after a certain amount. This is where JavaScript comes in. You can listen for the user's scroll event and then check what position the browser is in.

$(window).scroll(function(){
  if ($(window).scrollTop() >= 500){
    $('.obj').addClass('sticky');
  } else {
    $('.obj').removeClass('sticky');
  }
});

That's it for this tutorial. See you next time on PHP Trainee.

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.