Introduction:
In scrolling pages,sometimes we need a div allways fixed in top of the screen.
Main:
We can easily create sticky div’s using javascript.Please see the below sample Code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>"> <html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" xml:lang="en" lang="en"> <head> <title></title> <style type="text/css"> /*<![CDATA[*/ .ScrollingDiv { color: #00FF00; font-family:arial; font-size: 4pt; width:200px; } /*]]>*/ </style></head> <body> <br /> <br /> <br /> <div class="ScrollingDiv" >I am allways in Top</div> <div style="height:2000px;" ></div> <script type="text/javascript"> /*<![CDATA[*/ function ScrollBox(o){ this.box=NetByClassName(o.cls)[0]; this.clone=this.box.cloneNode(true); this.clone.style.position='absolute'; this.clone.style.zIndex='101'; this.os=o.offset||5; document.body.appendChild(this.clone); this.Scroll(); } ScrollBox.prototype.Scroll=function(){ var oop=this,p=NetPos(this.box),top=AllwaysTop(); this.clone.style.left=p[0]+'px'; this.clone.style.top=top+this.os+'px'; this.clone.style.visibility=top>p[1]?'visible':'hidden'; this.box.style.visibility=top>p[1]?'hidden':'visible'; this.to=setTimeout(function(){ oop.Scroll(); },50); } function NetPos(obj){ var rtn=[0,0]; while(obj){ rtn[0]+=obj.offsetLeft; rtn[1]+=obj.offsetTop; obj=obj.offsetParent; } return rtn; } function NetByClassName(nme,el,tag){ if (typeof(el)=='string') el=document.getElementById(el); el=el||document; for (var tag=tag||'*',reg=new RegExp('\\b'+nme+'\\b'),els=el.getElementsByTagName(tag),ary=[],z0=0; z0<els.length;z0++){ if(reg.test(els[z0].className)) ary.push(els[z0]); } return ary; } function AllwaysTop(){ if (window.innerHeight) return window.pageYOffset; else if (document.documentElement.clientHeight) return document.documentElement.scrollTop; return document.body.scrollTop; } new ScrollBox({ cls:'ScrollingDiv', offset:10 }); </script> </body> </html> |
Conclusion:
Hope,this helps,
Happy Coding.
great post as usual!