Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate position:fixed in jQuery

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 ;)

like image 824
Michael Lumbroso Avatar asked Jul 07 '10 07:07

Michael Lumbroso


3 Answers

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

like image 188
David Hellsing Avatar answered Nov 09 '22 12:11

David Hellsing


You can create a dummy visibililty:hidden element with the same width as that of the position:fixed element. Here is a sample:

<html>
<head>
  <script src="http://www.google.com/jsapi"></script>
  <script>
    google.load("jquery", "1.4.2");
    google.setOnLoadCallback(function() {
      $(document).ready(function(){
        var dummy = $('<div>dummy</div>').width( $('#header').width() + 'px').css('visibility','hidden');
        $('body').append(dummy);
      });
    });
    </script>
</head>
<body>
<div id="header" style="width:2000px;background:red;position:fixed;top:0;height:20px;">
    This is aheder with fixed position
</div>

<div style="height:1200px;background:green;">

</div>
</body>
</html>
like image 34
jerjer Avatar answered Nov 09 '22 10:11

jerjer


http://fixedheadertable.com/demo/multipletablesdemo.html

try this one instead :)

like image 1
Hailwood Avatar answered Nov 09 '22 12:11

Hailwood