Alessandro Lacava’s Blog

Google
 

February 16, 2007

How to display an element to the center of the browser

Filed under: Computer, JavaScript, CSS — alessandrolacava @ 12:55 pm

Sometimes you might need to display an element, for example a div, to the center of the browser. Here is an example of how you can do it using JavaScript and CSS.

JavaScript:
  1. function init()
  2. {
  3. // Reference to the element
  4. var loading = document.getElementById("loading");
  5. // The div's width, set within the CSS class
  6. var loadingWidth = loading.offsetWidth;
  7. // The div's width, set within the CSS class
  8. var loadingHeight = loading.offsetHeight;
  9. // The browser's body's width
  10. var documentWidth = document.body.clientWidth;
  11. // The browser's body's height
  12. var documentHeight = document.body.clientHeight;
  13. // Position the element absolutely
  14. loading.style.position = "absolute";
  15. // Center horizontally
  16. loading.style.left = (documentWidth - loadingWidth) / 2;
  17. // Center vertically
  18. loading.style.top = (documentHeight - loadingHeight) / 2;
  19. }

This code supposes you have a div element within your page with id="loading", for example:

HTML:
  1. <div id="loading" class="loading">Loading...</div>
  2. <!-- Other HTML code -->

The CSS class could be the following

CSS:
  1. .loading
  2. {
  3. border: 1px solid #90A6B8;
  4. background-color: #FFFF80;
  5. height: 100px;
  6. width: 300px;
  7. z-index: 1000;
  8. text-align: center;
  9. padding: 20px;
  10. color: #000000;
  11. font-size: 18px;
  12. font-weight: bold;
  13. }

The result should be that the browser displays the div--shown in the following figure--centered within the browser.

Centered Div Example

Centered Div Example

Of course you need to take care of the div hiding and showing according to your needs. For example, when an Ajax call starts/ends you might want to show/hide it , maybe with a "loading gif" within it.


January 16, 2007

How to set a link as if the mouse were over it using JavaScript

Filed under: Computer, JavaScript, CSS — alessandrolacava @ 4:53 pm

In order to do it when, for example, the page loads, use the following JavaScript trick:

HTML:
  1.  
  2. <script type="text/javascript">
  3. function markAsOver(linkId)
  4. {
  5. var elem = document.getElementById(linkId);
  6. elem.focus();
  7. }
  8. </script>
  9. </head>
  10.  
  11. <body onload="javascript:markAsOver('myLink');">
  12. <a id="myLink" xhref="someUrl.htm">This is selected</a>
  13. </body>
  14.  
  15. </html>

Of course you can use the CSS to take advantage of the previous code and make the link look as if it were active (selected). Here is an example:

CSS:
  1. a:hover, a:active, a:focus
  2. {
  3. color: red;
  4. }

If you use this code as CSS then the myLink link will be red as soon as the page loads.

Note: The a:focus pseudo-class works with Firefox.


Next Page »