SteelBlade94 SteelBlade94 - 1 year ago 175
HTML Question

How to display an iframe by clicking a button (JavaScript)

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>Welcome</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!

Answer Source

Add 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>Welcome</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 comment:

var iframeShowing = false;

function show() {
    var iframe1 = document.getElementById('iframe');
    iframe1.style.display = iframeShowing ? 'block' : 'none';
    iframeShowing = !iframeShowing;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download