Blog

6/recent/ticker-posts

How to Set an iFrame to Full Screen Mode with JavaScript

 Iframes are tools used in web development to display content from one website inside of another. The HTML attributes "width" and "height" establish the fixed size of iframes by default. Yet occasionally you might wish to show the iframe in full screen mode. In this article, we'll look at how to use JavaScript to set an iframe to run in full-screen mode.


We will be creating an iframe that displays the Microsoft Bing homepage. It has a fixed width and height, which means that it won't take up the entire screen.

To make the iframe go full screen, we need to add a few lines of JavaScript. First, we create a button that the user can click to toggle full screen mode. We also give the iframe a class called "fullScreen" that we'll use to style it later.


<button class="button" style="margin: 15px;">Fullscreen</button>

<iframe class="frame" src="https://www.wikipedia.com" width="300px" height="200px"></iframe>

<style>
    .fullScreen {
        width: 100vw;
        height: 100vh;
    }
</style>


Next, we use JavaScript to add an event listener to the button. When the user clicks the button, we change the class of the iframe to "fullScreen", which sets its width and height to 100vw and 100vh, respectively.

let BtnEle = document.querySelector(".button");
let frameEle = document.querySelector(".frame");
BtnEle.addEventListener("click", () => {
    frameEle.className = "fullScreen";
});


And that's it! When the user clicks the button, the iframe will go full screen.


Below is the full code of the iframe that displays the Microsoft Bing homepage

<!DOCTYPE html/>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sen Gideons Document</title>
<style>
    
    .fullScreen {
        width: 100vw;
        height: 100vh;
    }
</style>
</head>
<body>
<h1>iframe set to full screen mode</h1>
<iframe
class="frame"
src="https://www.bing.com"
width="300px"
height="200px"
></iframe>
<br/><br/><button class="button" style="margin: 15px;">Fullscreen</button>
<h3>Click the button above to set the iframe to fullscreen</h3>
<script>
    let BtnEle = document.querySelector(".button");
    let frameEle = document.querySelector(".frame");
    BtnEle.addEventListener("click", () => {
        frameEle.className = "fullScreen";
    });
</script>
</body>
</html>


Output:

Output after clicking on the fullscreen Button:




Conclusion:

setting an iframe to full screen mode is a simple task that can greatly improve the user experience on your website. By using JavaScript to toggle the iframe's class, you can easily make it take up the entire screen. We hope this blog post was helpful, if you have any questions, you can comment it below in the comment section.


Post a Comment

0 Comments

Ad Code

Responsive Advertisement

Hot Post