WhyPark Tips and Tutorials

A handy bit of Javascript: onload

A handy bit of Javascript: onload

As my fellow WPer's know, you can't edit the body tag of your WhyPark site. Many novice javascripters will think this means its impossible to do anything with javascript that requires the page to be fully loaded before the code is excuted. Fortunately, they're wrong.

Javascript has global event handlers, and one such event is the onload event that fires after the page is completely finished loading. Normally we would call the onload event from the body tag like this:

<body onload="alert('Hello World!');">

However, WhyPark does not give us the ability to edit the body tag, so that method is out. But we can accomplish that same concept by setting the global onload event handler like this:

<script type="text/javascript">
  window.onload = SayHi;

  function SayHi() {
    alert("Hello World!");
  }
</script>

This code can be placed anywhere in your template or even in individual content items to perform whatever we need done after the entire document has loaded. I use the following code to set the height of a div equal to the height of the related content div on AdminToolShed.com. That code looks like this:

<script type="text/javascript">
  function fixDiv() {
    var nHeight = document.getElementById('layer4').offsetHeight;
    document.getElementById('layer5').style.height= nHeight;
  }

  window.onload=fixDiv;
</script>

One caveat: You cannot use javascript in the event handler. It must call a function. So for example, this is incorrect:

window.onload = alert('Hello World!');

So, now that you know how to execute javascript code after the page loads, you can do really handy things like automatically placing the cusor in your site search text box or automatically scroll the related content items like this page is doing! (View this pages source to figure out how. *wink*)


Rate This Article:

WhyPark Tips and Tutorials


Home Site Map



Privacy Policy | Copyright/Trademark Notification