How to make <div> up and down while scrolling a page?

How can I make the div element move up and down the page when the user scrolls the page? (where this element is always visible)

+47
javascript jquery html css
Oct 28 '09 at 17:44
source share
6 answers

You want to apply a fixed property to the position style of an element.

position: fixed; 

Which browser do you work in? Not all browsers support a fixed property. Find out more about who supports him, who doesn't work and doesn't work here.

http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html

+64
Oct 28 '09 at 17:47
source share
β€” -

Just for a more animated and cute solution:

 $(window).scroll(function(){ $("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" ); }); 

And a pen for those who want to see: http://codepen.io/think123/full/mAxlb and fork: http://codepen.io/think123/pen/mAxlb

Update: and the non-animated jQuery solution:

 $(window).scroll(function(){ $("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"}); }); 
+57
Oct 10
source share

using only position:fixed is great when you don’t have a heading or logo at the top of the page. This solution will take into account how far the window scrolls and moves the div when scrolling your title. Then it will lock in place again when you return upstairs again.

 if($(window).scrollTop() > Height_of_Header){ //begin to scroll $("#div").css("position","fixed"); $("#div").css("top",0); } else{ //lock it back into place $("#div").css("position","relative"); } 
+10
Dec 27 '12 at 23:56
source share

Just add position: fixed; into your div style.

I checked and worked fine in my code.

+4
Dec 22
source share

Here is the jQuery code

 $(document).ready(function () { var el = $('#Container'); var originalelpos = el.offset().top; // take it where it originally is on the page //run on scroll $(window).scroll(function () { var el = $('#Container'); // important! (local) var elpos = el.offset().top; // take current situation var windowpos = $(window).scrollTop(); var finaldestination = windowpos + originalelpos; el.stop().animate({ 'top': finaldestination }, 1000); }); }); 
+4
Jan 07 '13 at 11:17
source share

You might want to check out Remy Sharp's recent article on fixed floating elements in jQuery for designers , which has a good video and a record on how to apply this effect in a client script

+3
Oct 28 '09 at 21:01
source share



All Articles