Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

I'm relatively new to jQuery, but so far what I've seen I like. What I want is for a div (or any element) to be across the top of the page as if "position: fixed" worked in every browser.

I do not want something complicated. I do not want giant CSS hacks. I would prefer if just using jQuery (version 1.2.6) is good enough, but if I need jQuery-UI-core, then that's fine too.

I've tried $("#topBar").scrollFollow(); <-- but that goes slow... I want something to appear really fixed.

like image 280
Timothy Khouri Avatar asked Nov 02 '08 19:11

Timothy Khouri


People also ask

How do I make a div always stay on top?

The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.

How do I fix a div at the top?

It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div.

How do I place a div at the top of the page?

If position: absolute; or position: fixed; - the top property sets the top edge of an element to a unit above/below the top edge of its nearest positioned ancestor. If position: relative; - the top property makes the element's top edge to move above/below its normal position.

How do I make a div sticky?

Use a <div> element with a class name "sticky". Use <p> and <h2> elements.


2 Answers

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div> 

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {     $('#myElement').css('top', $(this).scrollTop() + "px"); }); 

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

like image 196
nickf Avatar answered Sep 16 '22 16:09

nickf


For those browsers that do support "position: fixed" you can simply use javascript (jQuery) to change the position to "fixed" when scrolling. This eliminates the jumpiness when scrolling with the $(window).scroll(function()) solutions listed here.

Ben Nadel demonstrates this in his tutorial: Creating A Sometimes-Fixed-Position Element With jQuery

like image 32
Schmoove Avatar answered Sep 20 '22 16:09

Schmoove