Skip to content Skip to sidebar Skip to footer

Creating A Floating Box Which Stays Within A Div

I'm trying to create a div 'floater' which acts similar to a fixed div (stuck in a specific position regardless of scrolling), but when it hits the boundaries of the div it is with

Solution 1:

Okay folks, here is a complete solution. I've only tested this in Firefox and IE, but it should work across the board (I think). This is straight JavaScript and jQuery is not used. The first JS function makes sure the height returned works in various browsers.

Edit - I improved on this, see below.

<html>
<head>
<style type="text/css">
* {margin:0;padding:0;}
#header {height:300px;width:100%;background:#888;}
#main {height:800px;width:70%;background:#eee;float:left;}
#side {width:30%;height:auto;background:#ddd;float:left;position:relative;}
#floater {height:400px;width:90%;background:#dcd;top:0px;position:absolute;}
#footer {height:300px;width:100%;background:#888;clear:both;}
</style>
<script>
function getPageY() {
 var height = 0;
 if(typeof(window.pageYOffset) == 'number') {
  height = window.pageYOffset;
 }
 else if(document.body && document.body.scrollTop) {
  height = document.body.scrollTop;
 }
 else if(document.documentElement && document.documentElement.scrollTop) {
  height = document.documentElement.scrollTop;
 }
 return height;
}
onload=function() {
 window.onscroll = scroll;
 function scroll() {
  ybox.value = "this: "+getPageY();
  var f = document.getElementById("floater");
  var y = getPageY()-300; // minus header height
  var divh = document.getElementById("main").offsetHeight;
  if (divh > 400) { // greater than floater height
   divh -= 400; // minus floater height
   if (y < 0) y = 0;
   else if (y > divh) y = divh;
   f.style.top = y+"px";
  }
 }
}
</script>
</head>
<body>
<div id="header"></div>
<div id="main"></div>
<div id="side"><div id="floater">Float Content<br />
<input name="ybox" id="ybox"></div></div>
<div id="footer"></div>
</body>
</html>

This works, but with images it is extremely jumpy. I modified it to use a fixed position when it should be stuck in a position. Replace the three matching lines with this for a smoother result:

if (y < 0) {y = 0;f.style.position = "absolute";}
else if (y > divh) {y = divh;f.style.position = "absolute";f.style.top = divh+"px";}
else {f.style.position = "fixed";f.style.top = 0;}

Solution 2:

I've implemented this and its pretty good. http://net.tutsplus.com/tutorials/html-css-techniques/creating-a-floating-html-menu-using-jquery-and-css/. But this is done using jquery only. Ill let you know if icome across any links with just plain javascript.


Post a Comment for "Creating A Floating Box Which Stays Within A Div"