Previous Page
Next Page

Loading Multiple Frames at Once

It just takes a single link with a target attribute to change the content of a frame; that's simple HTML. To change the content of multiple frames with one click, you need JavaScript. The HTML files are trivial; all the action takes pace in Script 5.15. Two of the possible states the window can take are shown in Figures 5.12 and 5.13.

Script 5.15. JavaScript lets you load multiple frames with a single user click.

window.onload = initFrames;

function initFrames() {
     var leftWin = document.getElementById ("left").contentWindow.document;

     for (var i=0; i<leftWin.links.length; i++) {
        leftWin.links[i].onclick = setFrames;
     }
}

function setFrames() {
     document.getElementById("left"). contentWindow.document.location.href = this.id + ".
html";
     document.getElementById("content"). contentWindow.document.location.href = this.href;
     setTimeout("initFrames();",1000);
     return false;
}

Figure 5.12. The page looks like this initially.


Figure 5.13. But when a link is clicked, both frames change.


To load multiple frames at once:

1.
function initFrames() {
  var leftWin = document.getElementById("left"). contentWindow.document;

  for (var i=0; i<leftWin.links. length; i++) {
     leftWin.links[i].onclick = setFrames;
  }
}



The initFrames() function is pretty similar to what it's been previously in this chapter. It's called onload, as always. The function loops through the navigation bar (left) links. This time, it sets the onclick handlers to the setFrames() function.

2.
document.getElementById("left"). contentWindow.document.location. href = this.id + ".html";
document.getElementById("content"). contentWindow.document.location. href = this.href;
setTimeout("initFrames();",1000);

The setFrames() function first resets the left frame based on the id of the link that called it. The function then resets the content frame based on the HRef of the link that called ityes, we have access to that via JavaScript, so why not use it?

The function waits a second (by using setTimeout) and then calls the initFrames() function. This has to happen again because it's what sets the onclick handlers in the navigation bar, and as soon as we loaded a new navigation page into the bar, all those onclick handlers went away. In order to keep things working, they've all got to be reset for the new page, and this is how it's done.

3.
return false;



And finally, we return false, so the browser won't load the new page in.

Tip

  • If you click links in the navigation bar quickly, you'll get an unexpected result; a content page replaces the navigation bar. That's because the navigation page must finish loading before it is ready to accept the next click.



Previous Page
Next Page