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.
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.
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.
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.
Use a <div> element with a class name "sticky". Use <p> and <h2> elements.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With