Search code examples
javascripthtmlviewport

How to make viewport bigger


I'm trying to make a video play automatically (iframe) when it's in the viewport. The problem now is, that the video needs to be big, so in order for it to be in the viewport, it's almost impossible for a user to scroll to the section, so the video is deadcenter...

I'm wondering how I could solve that, if you have any ideas, please let me know.

I'm thinking about the functions which returns if an element is in the viewport which looks like this:

enter image description here

Maybe I can make the viewport bigger?


Solution

  • Well it's me again. I've solved this with a little "hack".

    In my html I added an abslute positioned element which is behind the iframe and has no content. Since this is a very small element, it is faster in the viewport and the video starts playing, eventhough the video isn't fully in the viewport.

    Not sure if this was the best solution but it worked for me :)

    Html

    <div class="js-viewport c-video-slider__viewport"></div>
    

    Css

    .c-video-slider__viewport {position: absolute; top 45%;}
    

    JS

    var vp = document.querySelector(".js-viewport");
    if (this.isInViewport(vp) != false) {...}
    isInViewport(el) {
        const rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <=
                (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <=
                (window.innerWidth || document.documentElement.clientWidth)
        );
    }