tonoslfx
tonoslfx

Reputation: 3442

jquery smooth scrolling in Chrome NOT in Internet Explorer

I am trying to a fixed header on top of the page. So when the user scroll down, the header stay up on top. However this is only work in Chrome, FireFox and Opera which scrolls smoothly.

If you have a look the code below. Open with IE and Google Chrome. You will see the difference! The header must stay in the wrapper.

Example Code

I would like to know how to make the scrolling smooth when repositioning objects inside the div elements when set to absolute to keep it floating at the top of the box.

HTML:

<div id="wrapper">
    <header>
        <h2>Title Header</h2>        
    </header>
    Content page
</div>

CSS:

#wrapper{
    height:200px;
    overflow-y:scroll;
    position:relative;
}

#wrapper > p {
    position: absolute;
    z-index: 0;

}
#wrapper header {
    background-color:#ccc;
    position: absolute;
    z-index: 10;
    display: block;
    top: 0px;
    padding:10px;
    width: 100%;
}

#wrapper header h2 { margin:0 }

Javascript:

$(function(){
    $('#wrapper').scroll(function(e){
         $('header').css('top',parseInt($('#wrapper').scrollTop())+'px');
    });
 });

Upvotes: 1

Views: 1156

Answers (1)

Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10179

I'd rather use this CSS and remove the JS for cross-browser compatibility:

// same CSS...
#wrapper p {
    margin-top: 50px; //no positioning just a top margin
    z-index: 0;

}
#wrapper header {
    background-color:#ccc;
    position: fixed; // from absolute to fixed
    z-index: 10;
    display: block;
    top: 0px;
    padding:10px;
    width: 100%;
}
//same CSS...

Demo.

Upvotes: 2

Related Questions