Skip to content Skip to sidebar Skip to footer

Change An Iframe's Src From Another Html File?

Well, I have my radio elements that update an iFrame with js code; and that works fine. Then I have my button below that creates an iFrame in a HTML Division that contains a bunch

Solution 1:

A simple way to do so is to get the button inside the iframe and set the event onclick like this

$(document.getElementById('iFrame2').contentWindow.document.getElementById("iFrame2Button")).click
   (function () 
   { 
          $("#iFrame1").attr('src','tests.php'); 
   })

Solution 2:

Assuming all the frames are in the same domain, this can be done like this:

<html>
    <head>
        <title>Main Page</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript">
             var change_iframe1_src = function(new_src) {
                 $("#iframe1").attr('src', new_src);
             }
        </script>
    </head>

    <body>
        <!-- frame for which we will change src attribute -->
        <iframe id="iframe1" src="" width="400" height="200" border="1"></iframe>        
        <!-- frame which includes your iframe2 with the buttons-->
        <iframe src="iframe.html" width="200" height="200" border="1"></iframe>
    </body>
</html>

Now in the iframe2 file attach a click handler for your buttons that should change the src attribute of the iframe1 by calling a function defined in the main page.

Example:

<html>
<head>
    <title>iFrame 2</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("button").click(function(e) {
                e.preventDefault();
                // call function in a parent frame - IMPORTANT LINE BELOW :)
                parent.window.change_iframe1_src(this.rel);
            })
        })
    </script>
</head>
<body>
    <button rel="iframe3.html">Change iframe src to iframe3.html</button>
    <button rel="iframe4.html">Change iframe src to iframe4.html</button>
</body>

The links in the iframe 2 page call the function which is defined in the parent window (the main page / the window which embeded the iframe2 page itself). That function (change_iframe1_src in this example) takes one argument which is a new url. The src attribute of the frame #iframe1 (your first frame) will be changed to this url.

Again, this works as long as all the frames are in the same domain.

Hope it helped :) Source


Post a Comment for "Change An Iframe's Src From Another Html File?"