Search code examples
jqueryeventsfullscreenchange

jquery fullscreenchange and on.click Event


I have a slider with responsive video's that can go fullscreen. When clicked on the poster image in fullscreen mode I want to get the .clientWidth of the image to set a div (.sp-layer) where the video's iframe is loaded in.

The fullscreenchange Events seem to work fine, but whenever I click on the link with the .on('click') Event, the fullScreenMode is undefined?

    this.fullScreenMode = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
    console.log("initial fullScreenMode: " + this.fullScreenMode);

    $(document).on('mozfullscreenchange webkitfullscreenchange fullscreenchange', function() {
        console.log('fullscreenchange Event fired');
        this.fullScreenMode = !this.fullScreenMode; 
        console.log('fullScreenMode: ' + this.fullScreenMode);

        if (!this.fullScreenMode) {
            console.log('we are not in fullscreen, do stuff');
            $('.sp-layer').css('width', '100%');    
        }
    });

    $('a.sp-video').on('click', function() {
        console.log('clicked on link');
        console.log('fullScreenMode: ' + this.fullScreenMode);

        if (this.fullScreenMode) {
            console.log('we are fullscreen, do stuff');
            var cW = $(this).children('img')[0].clientWidth;
            console.log('clientWidth of image: ' + cW);
            $(this).parent('.sp-layer').css('width', cW);
        }
    }); 

Solution

  • Change this.fullScreenMode to document.fullScreenMode in your click handler. In the click handler, this refers to the button a.sp-video, not the document.

    As in:

    $('a.sp-video').on('click', function() {
        console.log('clicked on link');
        console.log('fullScreenMode: ' + document.fullScreenMode);
    
        if (document.fullScreenMode) {...