jQuery: emulate CSS fixed positioning on mobile browsers

jQuery: emulate CSS fixed positioning on mobile browsers

How to emulate CSS fixed positioning on mobile browsers with jQuery.

As you know, mobile browsers often lack of support for the CSS fixed positioning. However, this feature can be easily reproduced by using absolute positioning combined with a dynamic adjusting of the top property via jQuery. Let's see the details.

We have the following HTML structure:

<body>
<ul id="nav">
	<li><a href="#">Link</a></li>
	<li><a href="#">Link</a></li>
	<li><a href="#">Link</a></li>
</ul>

<div id="content">...</div>
</body>

with the following styles:

#nav {
    width: 100%;
    height: 2em;
    background: #000;
    border-width: 0.3em 0;
    border-style: solid;
    border-color: #aaa;
    position: absolute;
    top: 0;
}

#nav li {
    float: left;
    height: 100%;
    margin-right: 1em;
}

#nav a {
    padding: 0 1em;
    height: 100%;
    display: block;
    text-decoration: none;
    color: #f60;
    line-height: 2;
}

#nav a:hover {
    background: #aaa;
    color: #fff;
}

#content {
    margin: 3em;
}

p {
    margin: 0;
    line-height: 1.4;
}​

With jQuery, we have only to calculate the difference between the top offset of the navigation menu and the scrollTop value of the browser window. Our dynamic adjusting takes place when a user scrolls the page:

var $windowTag = $(window);
var $fixedElement = $("#nav");
var fixedElementOffSet = $fixedElement.offset().top;

$windowTag.scroll(function() {

    var scrollTop = $windowTag.scrollTop();

    if (fixedElementOffSet < scrollTop) {
        $fixedElement.css('top', scrollTop);
    } else {
        $fixedElement.css('top', 0);
    }
});​

You can see the demo below.

Demo

Live demo