Reputation: 13
I am setting up a website and what I need is for when a button is clicked it changes the link in the iframe so it goes to another website. Here is what I got so far:
<script>
var id = 'http://www.aWebsite.com';
function link(){
id = 'http://www.aSecondWebsite.com'
}
</script>
<script>
document.writeln('<iframe name="heel"src="' + id + '" height="300" width="700"> </iframe>');
</script>
<button onclick="link()">Click Me</button>
I am not sure why when the button is clicked the id variable isn't changed?
Upvotes: 0
Views: 113
Reputation: 23396
Actually the value of id
is changed, but document.writeln()
is not in the link
function, hence it's not executed.
A quick-fix would be to move the document.writeln()
into link()
, but that would be a disastrous fix. document.write(ln)()
wipes out everything in the document, and creates a new one, when used after the page has been parsed. You need to do something like this:
function link() {
id = 'http://www.example.org';
document.getElementById('heel').src = id;
}
Then add your iframe element to a HTML, and remove the whole script with document.writeln()
.
<iframe id="heel" name="heel" src="http://www.example.com" height="300" width="700"></iframe>
EDIT
If you want to create a new iframe
element, you can do it like this:
function link() {
var frame = document.createElement('iframe'); // creates an iframe element
id = 'http://www.example.org';
frame.width = '700px'; // sets the width for the new iframe
frame.height = '300px'; // sets the height for the new iframe
frame.name = 'heel2'; // sets the name for the new iframe
frame.src = id; // sets the src for the new iframe
document.body.appendChild(frame); // appends the new iframe to body as a last element
}
Upvotes: 2