javascriptfancybox

Play bg video on close Fancybox popup


I have video on bg and button for open this video in popup Fancybox
I need when I open video in Fancybox popup video on bg is paused and when I close this popup video on bg is play
I tried this code but it works on the second attempt to close the popup
Fancybox ver 5.0

        const video = document.querySelector('.hero-section__video-bg video'),
            videoPlayBtn = document.querySelector('.hero-section__video-btn')

        videoPlayBtn.addEventListener('click', function () {
            video.pause()
        })

        window.addEventListener('click', function () {
            Fancybox.bind('[data-fancybox="video"]', {
                on: {
                    close: (fancybox, eventName) => {
                        video.play()
                    },
                }
            })
        })

Link to demo


Solution

  • I don't think you need window click handler. Fancy box event handler will kick in when you click on close button. So this would work.

    const video = document.querySelector('.hero-section__video-bg video'),
      videoPlayBtn = document.querySelector('.hero-section__video-btn')
    
    videoPlayBtn.addEventListener('click', function() {
      video.pause()
    })
    
    Fancybox.bind('[data-fancybox="video"]', {
      on: {
        close: (fancybox, eventName) => {
          video.play()
        },
      }
    });