Monday 1 July 2013

Sticky scroll Jquery

Simple JQuery for fixed position element

we have used this sticky jquery in many project in which we wanted their statically positioned sidebars to stick to the top of the page when you scroll down. 

when scrolling up a page, the sticky element needs to stop sticking when it returns to its original position. But I would say that almost equally important is having a bottom boundary on the page where the sticky element will stop sticking so that it doesn't spill into the footer or even outside of the page itself. With 1 options provided, the plugin will use the <body> element as the bottom boundary.

Example:

Header
Candy canes tart pie biscuit. Cupcake liquorice cake dessert tootsie roll applicake pastry. ...
In this example, we will create a simple webpage that consists of the header, the navigation and the content.



And, we will apply the sticky position to the navigation. 
But first, we will define the styles in the stylesheet, like so.
.sticky {
 position: fixed;
 width: 100%;
 left: 0;
 top: 0;
 z-index: 100;
 border-top: 0;
} 
Then, we will apply that class to the navigation conditionally with jQuery.
$(document).ready(function() {
var stickyNavTop = $('.nav').offset().top;

var stickyNav = function(){
var scrollTop = $(window).scrollTop();
     
if (scrollTop > stickyNavTop) { 
    $('.nav').addClass('sticky');
} else {
    $('.nav').removeClass('sticky'); 
}
};

stickyNav();

$(window).scroll(function() {
 stickyNav();
});
}); 
Finally, you can see the demo from the link below.

No comments: