I am trying to display an iframe when a button is clicked. I got the following JS code:
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = 'block';
}
I am trying to display an iframe when a button is clicked. I got the following JS code:
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = 'block';
}
and here is the HTML of my page:
<!DOCTYPE html PUBLIC>
<html>
<head>
<title>Wele</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="global.css"/>
<link rel="stylesheet" type="text/css" href="buttons.css"/>
<link rel="stylesheet" type="text/css" href="paragraphs.css"/>
<link rel="stylesheet" type="text/css" href="iframes.css"/>
<script type="text/javascript" src="files.js"></script>
</head>
<body>
<form> <button id="files" onclick="show()">Files</button> </form>
<iframe id="iframe" src="files.html" width="200" height="100"></iframe>
</body>
</html>
The script is inside an external file named files.js. When I test the code, it works, but the iframe only shows for 1 milisecond. What's wrong?
Thanks in advance for your answers!
Share Improve this question asked Oct 1, 2017 at 15:39 ThurinumThurinum 1483 silver badges13 bronze badges2 Answers
Reset to default 2Add type="button"
to your <button>
. As it is right now, it is inside a form, and without any type attribute — that way it defaults to type submit
, so when you click it, the page is submitted and disappears.
Also, change onclick="show()"
to onclick="show"
, or better yet — use .addEventListener()
instead.
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = 'block';
}
<!DOCTYPE html PUBLIC>
<html>
<head>
<title>Wele</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="global.css"/>
<link rel="stylesheet" type="text/css" href="buttons.css"/>
<link rel="stylesheet" type="text/css" href="paragraphs.css"/>
<link rel="stylesheet" type="text/css" href="iframes.css"/>
<script type="text/javascript" src="files.js"></script>
</head>
<body>
<form> <button type="button" id="files" onclick="show">Files</button> </form>
<iframe id="iframe" src="files.html" width="200" height="100"></iframe>
</body>
</html>
EDIT: Additional code in response to OP's ment:
var iframeShowing = false;
function show() {
var iframe1 = document.getElementById('iframe');
iframe1.style.display = iframeShowing ? 'block' : 'none';
iframeShowing = !iframeShowing;
}
The form is causing a page reload. You can stop that by simply adding a event.preventDefault(). function show(e) { e.preventDefault(); ...
However, you will need to inject the event parameter in the function call.
onclick="show(event)"
Another option you have is just remove the form tag and keep the button tag. That should do the trick.