I have tried to fullscreen a div using JavaScript. Here is my HTML and JS:
var elem = document.getElementById('fullscreenThis'); function openFullscreen() { if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } } document.getElementById('fullscreen').addEventListener('click', openFullscreen);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <body> <div id="fullscreenThis"> Here is some code I want to fullscreen </div> <button id="fullscreen">fullscreen</button> <script src="main.js"></script> </body> </html>
I have tried this in Firefox and Chrome.
Advertisement
Answer
var elem = document.getElementById('fullscreenThis'); function openFullscreen() { if (elem.requestFullscreen) { elem.requestFullscreen(); } } document.getElementById('fullscreen').addEventListener('click', openFullscreen);
<div id="fullscreenThis"> Here is some code I want to fullscreen </div> <button id="fullscreen">fullscreen</button>
Hi Rayyan,
First I think you want to target fullscreenThis
rather than body
, then I want to direct your attention to https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen
One useful snippet from this article is
It’s not guaranteed that the element will be put into full screen mode.
and also
An element that you wish to place into full-screen mode has to meet a small number of simple requirements:
- It must be one of the standard HTML elements or or . It is not a element.
- It must either be located within the top-level document or in an which has the allowfullscreen attribute applied to it.
Additionally, of course, the Feature Policy “fullscreen” permission must be granted.
I hope this helped you refactor your code in the right direction 🙂