javascriptfullscreenchange

"fullscreenchange" event isn't compatible with every browser (looking for Vanilla Javascript fix)


I am using the "fullscreenchange" event to apply the css I would like by adding or removing an ID (#showFullscreen) that will take dominance over the css already applied to .fullscreen.

    var fullscreen = document.getElementsByClassName("fullscreen");

    document.addEventListener("fullscreenchange", function() {
        if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
            fullscreen[0].setAttribute("id", "showFullscreen");
        } else if (!document.fullscreenElement || !document.webkitFullscreenElement || !document.mozFullScreenElement || !document.msFullscreenElement) {
            fullscreen[0].removeAttribute("id", "showFullscreen");
        }
     });

How can I get this code to work across all browsers using vanilla javascript?


Solution

  • As is described in this documentation bij W3Schools, you need to prefix the eventname dependent on the browser.

    // Includes an empty string because fullscreenchange without prefix is
    // also a valid event we need to listen for
    const prefixes = ["", "moz", "webkit", "ms"]
    var fullscreen = document.getElementsByClassName("fullscreen");
    var fullscreenElement = document.fullscreenElement || /* Standard syntax */
      document.webkitFullscreenElement || /* Chrome, Safari and Opera syntax */
      document.mozFullScreenElement || /* Firefox syntax */
      document.msFullscreenElement /* IE/Edge syntax */;
    
    prefixes.forEach(function(prefix) {
     document.addEventListener(prefix + "fullscreenchange", function() {
        if (fullscreenElement) {
            fullscreen[0].setAttribute("id", "showFullscreen");
        } else if (!document.fullscreenchange) {
            fullscreen[0].removeAttribute("id", "showFullscreen");
        }
     });
    });