• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 4. Frames, Frames, and More Frames > Sharing Functions Between Frames

Sharing Functions Between Frames

One common frame layout uses a permanent navigation frame and a content frame that might display a variety of different pages. If all those content pages need to call an identical JavaScript, it makes sense to put the function into the page that's always present instead of duplicating it for every possible content page. In Figure 4.10, we use this capability to have many pages share an identical function that returns a random banner image. This requires that part of the code be in the navigation frame and part in the content frame. Script 4.17 loads the pages into the frameset.

Figure 4.10. And here's the result of the scripts.

To use a function on another page:

							bannerArray = new Array("images/ redBanner.gif", "images/ greenBanner.gif", "images/ blueBanner.gif")


In Script 4.18, which is the navigation frame, start by creating a new array that contains all the possible banner images.

								function setBanner() {

Then, create a new function called setBanner().

								randomNum = Math.floor(Math.random() * bannerArray.length)

This line uses the Math.random() function multiplied by the number of elements in the bannerArray array to calculate a random number between 0 and the number of elements in the array.

								return (bannerArray[randomNum])

Here, we return the URL of the random banner image.

								onLoad="if (document.images) {document.adBanner.src=parent. left.setBanner()}"


Scripts 4.19, 4.20, and 4.21, which are in the content frame, set adBanner.src to be the new banner image returned by setBanner() in parent.left (the navigation frame). This is done when the page loads (by using the onLoad event handler) and only when document.images is true—otherwise, we'd be trying to change an image object for browsers that can't handle images.

Script 4.19. Call the common JavaScript function in the navigation frame to display a random image.

Script 4.20. And you can call it again…

Script 4.21. …and again.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint