aboutsummaryrefslogtreecommitdiff
path: root/src/component/VideoAuto.astro
blob: abb9c685b35dbf2467d616dd19957227e68eeef3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
---
const { src, thumb } = Astro.props;
---

<img src={thumb} data-video={src} alt="Video thumbnail" />

<script>
  const updateVideo = () => {
    document.querySelectorAll("img[data-video]").forEach((img) => {
      if (window.screen.width < 1000) return;
      const parent = img.parentNode;
      if (parent == null) {
        throw new Error("Invalid video");
      }
      const video = document.createElement("video");
      video.muted = true;
      video.defaultMuted = true;
      video.loop = true;
      video.autoplay = true;
      const source = document.createElement("source");
      source.src = img.getAttribute("data-video");
      video.appendChild(source);
      parent.insertBefore(video, img);
      parent.removeChild(img);
    });
  };

  window.addEventListener("load", () => {
    document.querySelectorAll("img[data-video]").forEach((img) => {
      const parent = img.parentNode;
      if (parent == null) {
        throw new Error("Invalid video.");
      }
      parent.addEventListener("updatevideo", updateVideo);
    });
  });
</script>