Fixed div box while scrolling window using javascript and css

fixed div while scrolling windows

fixed div  while scrolling windows

Have you used fixed div scroll ?

I think many of you have shown div box which at time of load page, it scrolls when we scroll window, but later on after reach at some specified pixed, div box remains at fixed position. Am i right ?

Such type of windows are very useful in case of advertisement or highlight some contents. However mostly it is used for google ads in blogs. So now i am showing that how you can do it ? Its a very easy simple, you just need to download my sample files. I have used pure javascript and css property for it. There is not any extra file load. I have used  google jquery CDN libray, about which you all are aware.

Javascript code :

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js”></script>
<script>
$(function () {

var msie6 = $.browser == ‘msie’ && $.browser.version < 7;

if (!msie6) {
var top = $(‘#comment’).offset().top – parseFloat($(‘#comment’).css(‘margin-top’).replace(/auto/, 0));

$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();

// whether that’s below the form
if (y >= top) {
// if so, ad the fixed class
$(‘#comment’).addClass(‘fixed’);
} else {
// otherwise remove it
$(‘#comment’).removeClass(‘fixed’);
}
});
}
});
</script>

You can see that code of fixed div scroll is very simple.  At time of initial it detects given div offset and then changed top position as fixed when it reaches at specified pixel. As per given example when top position will touch our given div box then , its css property will change to fixed. In this way while scrolling windows, our div box will be fixed on top.

View DEMO

Download File