Adding features to an existing set of code that you’ve never worked with is never easy, and under a tight deadline makes it even harder. Add to that the feature request requires adding video capability to an event template site for clients who don’t have any html experience, where we have little control over the dom before it is rendered to the page - meaning we have to rely on javscript to append elements - brings up a lot of questions.

We need to rely on a carefully executed process that requires html, css and javascript, and the help of a few custom fields inside the system which allow someone with no coding skills to edit.

First the custom fields are created so that the client can edit the video url that is being used and the poster frame for when the video is loading.

These values populate 2 hidden inputs on the page which we can hook into using javascript. As best practice I have namespaced these fields with a class js-** so we know that the input is being used by some javascript and hopefully allows other developers to get a quick understanding that it is used by another part of the system before they were to remove or amend it. As we have an existing module called imgToBackground I have made the new one called videToBackground to maintain consistency.

When the javascript runs it finds the videoToBackground div and then checks if the input field is populated. If not it skips the code block. If it is populated the video code will run.

$('.videoToBackground').each(function (index, el) {
    if ($('input#js-video-url').val()) {
        var video = document.createElement('video');
        video.src = $('input#js-video-url').val();
        video.setAttribute('poster', $('input#js-video-poster').val());
        video.setAttribute('autoplay', true);
        video.setAttribute('loop', true);
        video.setAttribute('playsinline', true);
        video.muted = true;
        $(this).prepend(video);
    }
});

And the SASS:

.videoToBackground {
    overflow: hidden;

    video {
        object-fit: cover;
        object-position: 50% 50%; 
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        transition: all 0.2s ease-in-out;
    }
}

This was the only extra features needed to add video to the existing template. The existing template already had content in the hero section which allows the video to have a height on mobile that is the content height plus some padding, and then on desktop has a set height of 100vh to force it to fill the viewport to the so called fold.

The beauty of this module is that it still allows the existing template features to be used and if no video is required the uer can simply remove the video url and the event site behaves as normal.