Simulate position:fixed in jQuery

Michael Lumbroso picture Michael Lumbroso · Jul 7, 2010 · Viewed 11.7k times · Source

I have a header that is larger than the width of the page so that I can't use position:fixed to set him on top of the page, because I absolutely need to be able to scroll horizontally. I don't think there is a CSS solution for this.

I made a sample of code to try to reproduce the effect of position:fixed, but there are undesired jumps. My code is as following :

$(window).scroll(function() {
            var y = $(window).scrollTop();
            $("#headertable").css('top', y+175);
});

Is there a way to make it really attached, like position:fixed? (Curiously, it is better displayed right now in IE than in FF, because it doesn't have this "jump" effect)

Please find an example here: http://jsbin.com/eyuya/7. The first table is with position:fixed, the other uses my code. That is the jumping effect I'm trying to avoid if there is a solution.

Edit:

Still haven't found a satisfying solution, I think I will use this in the end, because the site is meant to be used on IE and it doesn't seem like a miracle solution exists to attach a div to the viewport, and be able to scroll horizontally. I'm starting a bounty in case of somebody ran into this problem before and found a good solution.

Thanks for the people who already tried to answer this not as simple as it looks problem ;)

Answer

David Hellsing picture David Hellsing · Jul 19, 2010

You can wrap the element with a static positioned DIV to get scrollbars and then listen for the window scroll and position the fixed header according to the scrollLeft value:

var elem = $('#headertable');
var win  = $(window);
var wrap = $('<div>').css({
    width: elem.width(),
    height: elem.height()
});
elem.wrap(wrap);
win.scroll(function() {
    elem.css('left', win.scrollLeft()*-1);
});

Seems to work in IE/FF/Chrome:

http://jsbin.com/efuya3