Skip to main content

Letting Users add videos to custom websites.

Adding a video to an existing site and letting the client edit which video it is with no html skills whatsoever

Adding features to an existing set of unfamiliar code is never easy. And a tight deadline makes it even harder. This is compounded by the fact that the feature request requires adding video capability to an event template site for clients who don’t have any HTML or coding experience. More pressure gets added when we realise we have little control over the DOM before it is rendered to the page, meaning we have to rely on javascript to append elements. This 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 a 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 videoToBackground 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;
  }
}

These were the only extra features needed to add a 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 user can simply remove the video URL and the event site behaves as normal.