Changing contents of two frames – JavaScript tricks

Changing contents of two frames – JavaScript tricks cover image
  1. Home
  2. HTML
  3. Changing contents of two frames – JavaScript tricks

Here we look at changing contents of two frames simultaneously. This is a cool JavaScript trick and assumes you understand the language and HTML frames. If you are not familiar with these, you can find the appropriate tutorials on this site.

Firstly, we require an HTML file that contains a frameset.

<html>
<head>
<title>Changing two frames</title>
</head>
<frameset cols="30%,*">
<frame src="menu1.html" name="MENUFRAME">
<frame src="main1.html" name="MAINFRAME">
</frameset>
<body bgcolor="#FFFFFF">
</body>
</html>

The code above creates an HTML document containing two frames.

You can give any name to this file; I’ve used twoframes.html. Click on the link to view it. (Loads in another browser window)

Sponsored Links

Important points to remember when changing contents of two frames using JavaScript

Our aim is to have a link in menu1.html which when clicked, will change the contents of both frames – MENUFRAME and MAINFRAME.

Our menu1.html file is the important one. Here is the HTML code:

<html>
<head>
<title>LEFT FRAME</title>
</head>
<script type="text/javascript">
<!--
function change_frames(file1, file2)
   {
   parent.MENUFRAME.location=file1;
   parent.MAINFRAME.location=file2;
   }
//-->
</script>
<body bgcolor="#FFFFFF">
<a href="javascript:change_frames('menu2.html', 'main2.html')">
Change</a>
</body>
</html>

When the link is clicked, it loads menu2.html, which has a light blue background in MENUFRAME and main2.html having a yellow background in MAINFRAME.

Explanation of the JavaScript code

The function change_frames() accepts two arguments. These are files names passed to the function via JavaScript code in href of <a> tag. (Note: The href attribute of the <a> tag does not have a file URL as value but JavaScript code). This code is a function call and passes two parameters to change_frames().
Function change_frames() accepts the filenames, puts them in variables (file1 and file2) and uses these to change the contents of two frames. The contents are changed by loading these new files in the two frames employing the location property of the parent.frame object. Since we have already given names to our frames (MENUFRAME and MAINFRAME), we use these in the code.

The “menu2.html” file contains the same JavaScript code. However, in this case, we pass different filenames to change_frames() function. Have a look at its code by right clicking in the browser window and selecting View Frame Source (in N.N.) or View Source (in I.E.).

HTML