Vue Quick Shot - Fullscreen API

Vue Quick Shot - Fullscreen API

After yesterday's quick shot, today's should be simpler - using the Fullscreen API. This is one of the simplest and most useful API's out there. If a browser supports it (currently at near 100%) than all you need to enable fullscreen on your web page is the requestFullscreen DOM method.

For example:

document.querySelector('#myCat').requestFullScreen();

The API supports more options (events and exiting fullscreen mode via code), but let's look at a simple example with Vue.js.

Let's begin with our HTML. I'm going to include an image and a button to enable fullscreen access. The button will only show up if the Fullscreen API is enabled. Note the use of ref on the image so I can grab it easier via Vue later.

<div id="app" v-cloak>
  <h2>Cats</h2>
  <img src="https://placekitten.com/400/200" ref="catpic"><br/>
  <button v-if="showFSButton" @click="fullscreenCats">Full Screen Cats</button>
</div>

Now let's look at the JavaScript:

const app = new Vue({
  el:'#app',
  data: {
    showFSButton:false
  },
  created() {
    if(document.fullscreenEnabled) this.showFSButton = true;
  },
  methods:{
    fullscreenCats() {
      this.$refs.catpic.requestFullscreen();
    }
  }
})

So my data just includes the boolean for whether or not the button will show up. My created method checks if the feature exists and if so will set the value to true.

Finally, the button's click event uses the API to open the image in fullscreen mode. And that's it! Here's a full demo in CodePen, and yes the button works in the embed.

See the Pen Vue + Fullscreen by Raymond Camden (@cfjedimaster) on CodePen.

As always, let me know if this helps you!

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments