skip to Main Content

i have the below code
this code adds a button that makes an iframe go fullscreen when clicked
i need to add a javascript code to automatically click this button when site loads and the iframe becomes fullscreen when site loads
what code should i add and where should i add it ?
Thanks
.

<center><button id="full" style="color:blue;margin: 15px;;font-size:300%;" onclick="goFullscreen('cowboy'); return false">Fullscreen</button></center>
<script>
function goFullscreen(id) {
    var element = document.getElementById(id);
    if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullScreen) {
      element.webkitRequestFullScreen();
    }
    
}
</script>

.
i found some codes searching about this
but i dont actually know where to put them in my code

2

Answers


  1. Browsers do not allow websites to trigger fullscreen mode on load. There must be a user interaction. You can’t fake one by simulating clicking on a button with JS; the browser knows the difference.

    Login or Signup to reply.
  2. In javascript, you can create something called IIFE (Immediately Invoked Function Expression). These are functions which get immediately invoked by default. You can just update your code like this to achieve this:

    (function()
        {
        ...
        Your code
        ...
        }
    )()
    

    I.e., by just wrapping your function inside () and calling it immediately by adding () in the end.

    Here is the complete HTML code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <center><button id="full" style="color:blue;margin: 15px;;font-size:300%;">Fullscreen</button></center>
      <script>
        (function (){ 
            // alert is to test if it is working, you can erase this line
            alert("hi")
            var element = document.getElementById("full");
            if (element.mozRequestFullScreen) {
              element.mozRequestFullScreen();
            } else if (element.webkitRequestFullScreen) {
              element.webkitRequestFullScreen();
            }
            
        })()
        </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search