I have looked on many websites but none of them seem to work right or I don't understand them. I would like a simple button that refreshes a certain iframe. The button would be on the parent page and the iframe name is "Right".
Asked
Active
Viewed 4.3k times
2 Answers
25
There are many ways to do this. Assuming this iframe
markup:
<iframe name="Right" src="http://www.example.com"></iframe>
We can do it with a function call:
HTML
<button onclick="refreshIframe();">Refresh Iframe</button>
JS
function refreshIframe() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
}
Or with inline JS:
<button onclick="var ifr=document.getElementsByName('Right')[0]; ifr.src=ifr.src;">Refresh Iframe</button>
Or using an event listener:
HTML
<button id="iframeRefresher">Refresh Iframe</button>
JS
window.onload = function() {
document.getElementById('iframeRefresher').addEventListener('click', function() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
});
}
Same as above, now with support for IE <= 8 and using a function in the global scope as handler instead of an anonymous one:
HTML
<button id="iframeRefresher">Refresh Iframe</button>
JS
window.onload = function() {
var refresherButton = document.getElementById('iframeRefresher');
if (refresherButton.addEventListener)
refresherButton.addEventListener('click', refreshIframe, false);
else
refresherButton.attachEvent('click', refreshIframe);
}
function refreshIframe() {
var ifr = document.getElementsByName('Right')[0];
ifr.src = ifr.src;
}
All of this without even touching jQuery or any other library.
Which of these you should use? Whichever you consider more maintainable and readable. Just avoid global vars whenever possible. I'd personally avoid inline JS with the markup, and the listeners seem to be unnecessary, but that's just me. Choose whichever suits you better.

Fabrício Matté
- 69,329
- 26
- 129
- 166
-
Woah! I never thought that there were so many ways to do this! I wish someone could put this on a site about iframes! Thanks! – user1373771 Jul 03 '12 at 00:25
-
@user1373771 no problem, you can tick this as the accepted answer when you have time if that's all. `:P` – Fabrício Matté Jul 03 '12 at 01:04
-3
Add new id
in your iframe and try below code.
var iframe = document.getElementById('FrameId');
$("button").click(function() {
iframe.src = iframe.src;
}):

Dips
- 3,220
- 3
- 20
- 21
-
1OP said `name`, not `id`. There's no jQuery in the tags or anywhere in the question either. And you have invalid syntax at the end. – Fabrício Matté Jul 02 '12 at 01:59