How To: Fix Element Position After Some Scroll Using jQuery

Share

Later today surfing on web , found one website having static ads on sidebar. What happens is after some scroll ads got fixed and remain at same position till end. So wondering how it has been done , I tried it using jQuery.

The Trick

The trick is simple. Just calculate the distance between element and the browser top and fix the position if it is less than scrollTop.

Look at the code:

(function($){
			$.fn.scrollFixed = function(params){
			params = $.extend( {appearAfterDiv: 0, hideBeforeDiv: 0}, params);
			var element = $(this);

			if(params.appearAfterDiv)
				var distanceTop = element.offset().top + $(params.appearAfterDiv).outerHeight(true) + element.outerHeight(true);
			else
				var distanceTop = element.offset().top;

			if(params.hideBeforeDiv)
				var bottom = $(params.hideBeforeDiv).offset().top - element.outerHeight(true) - 10;
			else
				var bottom = 200000;				
			
				$(window).scroll(function(){	
					if( $(window).scrollTop() > distanceTop && $(window).scrollTop() < bottom ) 		
						element.css({'position':'fixed', 'top':'5px'});
					else
						element.css({'position':'static'});				
				});			  
			};
		})(jQuery);

Place the following code where you need to fix the element.

$(document).ready( function(){
	$("#scrollingDiv").scrollFixed({appearAfterDiv:'.sidebar p', hideBeforeDiv:'.footer'});
	$("#scrollingDiv1").scrollFixed({hideBeforeDiv:'.footer'});
});

 

Here is the working Demo

Your opinions and comments are welcome.

  • August 7, 2011
8 Best Free Stock Video Websites for Tiktok, Reels, and Shorts Top 5 PHP Frameworks: Fast and Secure