Lai Yu-Hsuan Lai Yu-Hsuan - 3 months ago 14
CSS Question

how to prevent a div leaving out of screen?

I want to do something like the "How to Format" on Ask Question page of stackoverflow.

Originally the

div
has
position:relative
. When any part of the
div
is out of screen, it becomes
position:fixed
.

How to implement it?

Edit: More precisely, what I want is:

At beginning, the
div
is Xpx from the top of window.

When I scroll down (X+Y)px, normally, the top Ypx part of the
div
will be hidden.

But I hope the whole
div
be fixed on the top of window. i.e. {position:fixed;top:0}

And if I scroll up back, the
div
will go back to Xpx from the top of window.

More more precisely, I want a more beautiful code for this:

$(document).ready(function()
{
var e = $('#myDiv');
var offsetTop = e.offset().top;
var positionTop = e.position().top;

$(window).scroll(function() {
if($(window).scrollTop() > offsetTop) {
e.css({'position' : 'fixed', 'top' : '0px'});
}
else {
e.css({'position': 'relative', 'top': positionTop});
}
});
});

Answer
$(document).ready(function()
{
    var e = $('#myDiv');
    var jWindow = $(window);
    var offsetTop = e.offset().top;
    var positionTop = e.position().top;

    jWindow.scroll(function()
    {
        if(jWindow.scrollTop() > offsetTop)
            e.css({'position':'fixed', 'top':0});
        else
            e.css({'position':'relative', 'top':positionTop});
    });
});