Search code examples
javascriptvideohtml5-video

Play Video as Background Video and not open in new window


I have a section with a background video and by default the video is paused. When the user clicks on the "Play Video" button, the video opens in a new window which I don't want.

I want to play the video in the same browser live the bmw video in my examples.

Here is the video of my website: streamable.com/6of5h9

Here is the video, i want to copy the effect for my website: streamable.com/xiq97z

How can I do so the video plays as background image?

The code used to play and pause the video:

const vidBtn = document.querySelectorAll('.kb-video-btn')
    if (vidBtn.length !== 0)
        Array.prototype.forEach.call(vidBtn, function (el) {
            if (el.classList.contains('play')) {
                el.addEventListener('click', function () {
                    let p = el.parentNode.parentNode.parentNode.parentNode
                    let v = p.querySelector('video')
                    if (v.playing) {
                        v.pause() // v.currentTime = 0;
                        return
                    }
                    v.autoplay = true
                    v.play()
                })
            }
        })

Solution

  • Make sure you have the playsinline attribute to your video tag in html.

    <video id="bg-video" playsinline>
        <source src="your-video.mp4" type="video/mp4">
    </video>
    

    This should tell the browser to play the video inline within the current document, rather than launching it in a separate window or play in fullscreen mode. This is good practice for mobile browsers too.