/    Sign up×
Community /Pin to ProfileBookmark

What is the easiest way to make a div seem to float on the page so when the page is scrolled up and down the div stays still in relation to the window rather than going up or down?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@KorSep 06.2007 — Simply adjust the element position (in [B]position:absolute[/B]!) according to the scroll position, on using onscroll event. There are differences between Moz (and compatible), IE in standard mode (and compatible), IE is quirks mode (and compatible) in capturing the scroll position. A simple example on keeping a div on top/left corner of the window onscroll:
<i>
</i>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Untitled Document&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt;
&lt;meta http-equiv="Content-Style-Type" content="text/css"&gt;
&lt;meta http-equiv="Content-Script-Type" content="text/javascript"&gt;
&lt;style type="text/css"&gt;
html body{
margin:0;
padding:0;
}
#mydiv{
width:200px;
height:50px;
position:absolute;
left:0px;
top:0px;
background:#ff0000;
}
&lt;/style&gt;
&lt;script type="text/javascript"&gt;
onscroll=function(){
var obj=document.getElementById('mydiv'), Y;
Y=window.pageYOffset?window.pageYOffset:document.documentElement?document.documentElement.scrollTop:document.body.scrollTop;
obj.style.top=Y+'px';
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id="mydiv"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

insert some <br> to have a scroll
Copy linkTweet thisAlerts:
@bokehauthorSep 06.2007 — Thanks!
×

Success!

Help @bokeh spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...