Forum Moderators: open
I would like to create a floating "window" (actually a div), that would scroll along with the user as the page is scrolled. Is there a cross-browser javascript based implementation for it? (More specifically, what is the code to cause a div element to scroll along with the user?)
Thanks in advance!
For Internet Explorer you'll indeed need some script, in combination with position: absolute for the div.
<style type="text/css">
#theDiv {position: fixed; left: 10px; top: 150px; }
</style>
<!--[if IE ]>
<style type="text/css">
#theDiv {position: absolute; }
</style>
<![endif]-->
..
<div id="theDiv">watch me <b>not</b> moving...</div>
..
<script language="JScript">
if (document.recalc && document.body.attachEvent) {
theDiv.style.setExpression("top", "document.body.scrollTop + 150");
document.body.onscroll=function(){document.recalc(true)};
}
</script>
Note the the conditional comments and the script language: JScript, as non-IE browsers need not take notice of all that IE-only stuff.
However, I still have a little bit of problem with the code you have. Since I have to write that bit of script to the browser through Javascript in real time, I have been tinkering with the JScript bit a little bit, but every time I try assigning the script into the script tag, IE refuses to run the script. What am I doing wrong?
This is the bit of code I'm having trouble adapting:
} else if (sniffer.ie5) {
newDiv.setAttribute("style","position: absolute; width: 100%; background-color:#ffeeee; color:#ffeeee");
var ieScript = document.body.appendChild(document.createElement('script'));
ieScript.id='iescript';
ieScript.language='JavaScript';
ieScript.innerHTML="if (document.recalc \&\& document.body.attachEvent) { newDiv.style.setExpression(\"top\", \"document.body.scrollTop + 150\"); document.body.onscroll=function(){document.recalc(true)};}";
(I escaped the "'s to make sure they can fit into the innerHTML property. However, it doesn't seem to work).
Thanks for all the help!
Then again, the need to try to concatenate the contents of script elements within the same document suggests that there is some confusion going on. Time to get back to basics. Unravel those strings!
I seem to remember, too, that one of the majors doesn't like the CSS strings set on the style object as if it where a normal attribute. If you want to set all styles at once, then you'll have better luck assigning a predefined class, or using the cssText property of the style object.
else if (sniffer.ie5)
{
newDiv.style.cssText
= "position: absolute; width: 100%; background-color:#ffeeee;"
+ "color: #ffeeee";
if (document.recalc && document.body.attachEvent)
{
newDiv.style.setExpression("top", "document.body.scrollTop + 150");
document.body.onscroll=function(){ document.recalc(true) };
}
}