Last active
October 30, 2022 21:34
-
-
Save mbround18/e4853df98392eb8569a4fd4042723859 to your computer and use it in GitHub Desktop.
Video Background Script for dev.to Article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function videoBackground() { | |
const body = document.querySelector("body"); | |
const background = body.style.backgroundImage | |
.replace('url("', "") | |
.replace('")', ""); | |
const parts = background.split("."); | |
const extension = parts[parts.length - 1]; | |
let type; | |
console.log({ background, extension }); | |
switch (extension) { | |
case "avi": | |
type = "video/avi"; | |
break; | |
case "ogv": | |
type = "video/ogg"; | |
break; | |
case "mp4": | |
type = "video/mp4"; | |
break; | |
default: | |
return; | |
} | |
if (type) { | |
let videoBackground = document.querySelector("#video-background"); | |
if (!videoBackground) { | |
videoBackground = document.createElement("video"); | |
videoBackground.id = "video-background"; | |
videoBackground.autoplay = true; | |
videoBackground.muted = true; | |
videoBackground.loop = true; | |
body.appendChild(videoBackground); | |
} | |
let source = document.querySelector("#video-background source"); | |
if (!source) { | |
source = document.createElement("source"); | |
videoBackground.appendChild(source); | |
} | |
source.src = background; | |
source.type = type; | |
} | |
} | |
videoBackground() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment