views:

191

answers:

1

Hi there,

I need to make it so that an element which would normally (depending on resolution) be off the bottom of the viewable area of a page, be floated at the bottom of the page and follow tha page down when scrolled (in a similar way to the effect of position:fixed in css).

However I need that element to then stop and stay where it is when it reaches where it would have been naturally, if that makes any sense!

Ideally if the css/js isn't supported the element should also appear in its 'natural' position.

Any ideas on the best way to deal with this ? Anyone know of any existing jQuery plugins that might help ?

Many thanks,

Stu

+2  A: 

This is how I accomplished this on a client site:

JavaScript (using jQuery):

if( !$.browser.msie || ($.browser.msie && $.browser.version > 6) ){
    $('body').append('<div id="listener" rel="generated">&nbsp;</div>');
    $(window).scroll(function () { 
     if($('#listener').offset().top > 150){
      $('body:not(.fixmenu)').addClass('fixmenu');
     }else{
      $('body.fixmenu').removeClass('fixmenu');
     }
    });
}

CSS:

#listener{
    position: fixed;
    top: 0;
    right: 0;
    height: 1px;
    width: 1px;
}
#page #submenu{
    position: absolute;
    top: 85px;
    z-index: 3;
}
.fixmenu #submenu{ position: fixed; }

The technique: dynamically generate an invisible "listener" div with fixed positioning in the top right corner of the page. When that listener is 150 pixels (or insert your arbitrary number here) or more from the top of the page, add the "fixmenu" class to the <body>. From here, use CSS to change the positioning of the menu from absolute to fixed.

Since IE6 does not support fixed positioning, I chose to exclude it.

cpharmston
Great stuff, many thanks!
stukerr
Worth noting: since I wrote this code, jQuery deprecated $.browser. You may want to look into $.support as an alternative.
cpharmston