user1129274
user1129274

Reputation: 101

change the src of an iframe using javascript

<table>
  <tr>
    <td>one</td>
    <td>two</td>
  </tr>
  <tr>
    <td>three</td>
    <td>four</td>
  </tr>
</table>

<div id="numbers">
  <iframe name="letters" src="">
  </iframe>
</div>

I'd like to have the ability to click on any cell in the table, grab the value inside, show the div and append the iframe src based on the cell's value. When the user clicks on the cell again the iframe becomes blank and the div is hidden.

For example: click cell one, show the div with the iframe src="/one.html". Click it again, hide the div with a blank iframe.

Thanks in advance!

(Please, no jQuery answers.)

Upvotes: 2

Views: 15355

Answers (3)

qw3n
qw3n

Reputation: 6334

Added ids to some of the HTML elements.

<table id="table">
  <tr>
    <td>one</td>
    <td>two</td>
  </tr>
  <tr>
    <td>three</td>
    <td>four</td>
  </tr>
</table>

<div id="numbers">
  <iframe id="iframe" name="letters" src="">
  </iframe>
</div>

And the javascript

document.getElementById('table').onclick=function(e){
  e = e || window.event;
  e=e.target || e.srcElement;
  if(e.tagName.toLowerCase()=='td'){
    var page = e.innerHTML,iframe=document.getElementById('iframe');
    if(iframe.src.indexOf(page)>-1){
      document.getElementById('numbers').style.display='none';
    }
    else{
      document.getElementById('numbers').style.display='block';
      iframe.src='/'+page+'.html';
    }
  }
}

Upvotes: 0

user319198
user319198

Reputation:

It should be something like below.Call this function on onclick event of td and pass desired src in parameter.

  <script type=”text/javascript”>
    function changeURL(srcvalue)
    {
    document.getElementById('letters').src=srcvalue;
    }
    </script>

Upvotes: 0

rekire
rekire

Reputation: 47975

Without adding an id to the iframe use this:

document.getElementsByTagName("iframe")[0].src="http://example.com/";

Or based on the name:

document.getElementsByName("letters")[0].src="http://example.com/";

If you would add a id:

<iframe name="letters" id="letterframe" src="" />

document.getElementById("letterframe").src="http://example.com/";

Upvotes: 4

Related Questions