Element on screen while scrolling using JQuery

There are many plugins which are doing this function, but I dont always think we need to attach a whole file when we can write 10 lines of code. This time, the feature I am going to discuss is how to keep an element in view while scrolling down. I like to use it in projects in which the page is longer then a view port and the client needs to scroll down to reach the end of the content or 1 page website maybe and we need to have a button ( ‘Get a Quote’ or ‘Contact us’ maybe ) which follows the scrolling. Hare is the code with short explanations of how it works in simple steps.

Include JQuery

This is rule one, everytime you would like to use JQuery. I bet you know that by now.

Create the scrolling element

Create the element which you would like to scroll with the viewport. Notice that we are using an id=”scrolling”.

Your content in here

Add a JQuery ‘listener’

The code below executes the ‘do stuff here’ code everytime the user scrolls. We are going to use this function to select our element and make it follow the screen.

$(window).scroll(function() {
do stuff here...
});

Animate the element

So, we reached the last step. We select the id of our element called scrolling and we use 2 functions – stop and animate. We use .stop, just in case the user has scrolled multiple times in different directions, this function is going to execute only the last scroll. Animate is to make the moving a little smoother. We change marginTop by the pixels the user has scrolled and add 30 just to push it down a little more. The ‘slow’ at the end is the duration of execution, which can be changed to fast or milliseconds by your choice. 1 second = 1000ms. Easy tutorial, huh?

$(window).scroll(function(){
$("#scrolling")
.stop()
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
});