nakb
nakb

Reputation: 341

Link loads in new page, not iframe

OK, I've not used iframes for a long time but this problem is so basic I must be missing something really obvious.

I have a page (Page A) containing a link (to Page B in the same domain/folder as the parent) that I want to open in an iframe in Page A.

pageA.html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page A</title>
</head>
<body>
<a href="/pageB.html" target="tgt">Load ...</a><br>
<iframe id="tgt"></iframe>
</body>
</html>

pageB.html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page B</title>
</head>
<body>
<p>This is a test. Should load in iframe.</p>
</body>
</html>

When the link is clicked pageB opens in a new page (as if the target id isn't present), not in the iframe in pageA.

What am I doing wrong?

=========================================================

OK, sorted that but now I need to do this using php generated JavaScript. Here is a very minimal example:

pageA.php (parent page):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page A</title>

<?php
$srcPage = "/pageB.html";
echo "
<script>
function loadIframe() {
    window.alert('Clicked, loading $srcPage');
    document.getElementById('tgt').attr('src', '$srcPage');
}
</script>
";?>

</head>

<body>
<p id="load" onclick="loadIframe()">[Click me to load] ...</p>
<iframe id="tgt" name="tgt"></iframe>

</body>

</html>

pageB.html (page to load - same as before):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page B</title>
</head>

<body>

<p>This is a test. Should load in iframe.</p>

</body>
</html>

The script executes (alert is displayed) but the page doesn't load.

Thanks

Nigel

Upvotes: 0

Views: 152

Answers (1)

DigitalDouble
DigitalDouble

Reputation: 1768

You should add the attribute name="tgt" to your iframe.

open link in iframe

For your second question, you mixed jquery with plain javascript. This is how you change the src of an iframe using plain javascript:

document.getElementById('iframeid').src = '$srcPage'

Upvotes: 3

Related Questions