Fullscreen Toggle component in VueJS

In this post we will see how to create a VueJs component that will toggle fullscreen mode in your browser.

I took this code from W3Schools: https://www.w3schools.com/howto/howto_js_fullscreen.asp
and integrated it into a VueJS component. Below is the full code for full screen toggle component.

It’s basically very simple logic. fullScreenMode data property is initially false, it is changed to opposite value on click of the button. watch is used to look for change. when fullScreenMode property changes, openFullScreen or closeFullscreen is triggered.

const FullScreenMode = Vue.component('full-screen-mode', {
  data: function () {
    return {
      fullScreenMode: false, 
    }
  },

  watch:{

    fullScreenMode: function(){
      if(this.fullScreenMode == true){
        this.openFullscreen();
      }
      else{
        this.closeFullscreen();
      }
    
    }

  },


  methods:{

    openFullscreen:function()  {

      var elem = document.documentElement;

      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      } else if (elem.mozRequestFullScreen) { 
        elem.mozRequestFullScreen();
      } else if (elem.webkitRequestFullscreen) { 
        elem.webkitRequestFullscreen();
      } else if (elem.msRequestFullscreen) { 
        elem.msRequestFullscreen();
      }    
      
    },
  
    closeFullscreen:function() {
      
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) { 
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) { 
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) { 
        document.msExitFullscreen();
      }
    
    }


  },
  template: 
  
    `
    <template>
      <button @click="fullScreenMode = !fullScreenMode">
        Toggle Fullscreen
      </button>
    </template>
    `         
});

Leave a Reply

Your email address will not be published. Required fields are marked *