davidlee
davidlee

Reputation: 6167

Javascript: have div always remain at the top when it reaches the top edge of browser with jquery

how to have a div that always stay on the screen? Lets say i have a div at the left hand site. When the browser is scroll to the bottom, the div will remain there ONLY when its' top reaches the top edge of browser screen so that it will not be hidden. I am using jquery too.

Thank you.

Upvotes: 1

Views: 3472

Answers (5)

Murugesh
Murugesh

Reputation: 820

Keep your div position: fixed;

Upvotes: 0

g023
g023

Reputation: 857

/* PlugTrade.com - Sticky Top jQuery Plugin */
jQuery.fn.sticky_top = function () {
    /* check for our hidden div.. create it if it doesn't exist */
    if (!this.find("#sticky_top").length > 0)
        this.append("<div id='sticky_top' style='display:none'>"+this.css('top')+"</div>");

    var thisdiv = this;

    $(window).bind('scroll', function(e){
        var initval = thisdiv.find("#sticky_top").text();
        var wintop = $(window).scrollTop();
        var boxtop = initval.replace(/px/i, "");

        if(wintop >= boxtop)
        {
            if ( $.browser.msie ) 
            {
                thisdiv.css('top', wintop+'px');
            } else {
                thisdiv.css('position', 'fixed');
                thisdiv.css('top', '0');
            }
            // console.log(boxtop+':'+wintop);
            /* thisdiv.css('top', wintop+'px'); */
        }
        else
        {
            thisdiv.css('position', 'absolute');
            thisdiv.css('top', initval);
        }
    });
}

You can use like this:

$('#div1').sticky_top();

Upvotes: 0

user372551
user372551

Reputation:

here is a Good ScreenCast By RemySharp Regarding this Issue

http://jqueryfordesigners.com/fixed-floating-elements/

Demo Page :

http://static.jqueryfordesigners.com/demo/fixedfloat.html

Upvotes: 3

sjobe
sjobe

Reputation: 2837

If you want it to always stay in thesame place, you can use the css property position: fixed; else you can use a combination of $(window).scroll() and .scrollTop(); to detect where your div is in relation to the screen and apply the right positioning.

Upvotes: 0

jAndy
jAndy

Reputation: 236092

You need to invoke .scrollTop() on the window and compare that with the offset top value from that DIV.

$(window).bind('scroll', function(e){
    var $div = $('.top').
        sTop = $(window).scrollTop();

    if($div.offset().top <= sTop)
        $div.css('top', sTop);
    else
        $div.css('top', '100px');
});

Whereas in this example, .top is the element which should stay at top.

Example: http://www.jsfiddle.net/2C6fB/8/

Upvotes: 0

Related Questions