Moving, Hiding and Changing the Contents of a Layer in Javascript

This simple example shows you how to move a layer, show and hide a layer and change the contents of a layer dynamically from Javascript. This kind of layer manipulation in fundamental to all web 2 applications.

This uses a randomly generated number to move the layer. This also uses document.body.scrollTop to adjust for scrolling and innerHTML to write to the layer.

 1. <html>
 2. <head>
 3. <title>Layer Properties</title>
 4. <script>
 5. function MoveLayer(){
 6.     var x = document.getElementById("mycontainer").style;
 7.     x.top  = parseInt(document.body.scrollTop) + Math.round(Math.random()*200); 
 8.     x.left = parseInt(document.body.scrollLeft) + Math.round(Math.random()*200);
 9. } 
10. function HideLayer(){
11.     var x = document.getElementById("mycontainer").style;
12.     x.visibility = (x.visibility == "visible" ? "hidden" : "visible");
13. }
14. 
15. function WriteToLayer(){
16.     document.getElementById("mycontainer").innerHTML="Now I've overwritten the original stuff"
17. }
18. </script>
19. </head>
20. <body>
21. 
22. <a href="javascript:HideLayer()">Hide/Unhide Layer</a>
23. 
24. <div style="position:absolute;visibility:visible" id="mycontainer">
25.     <a href="javascript:MoveLayer()">Move Layer</a> | 
26.     <a href="javascript:WriteToLayer()">Overwrite Layer</a>
27. </div>
28. 
29. </body>
30. </html>
Hide line numbers