For this html:
<html>
<div id="vids">
<video id="vid-1" src="vid1.mp4">
</video>
<video id="vid-2" src="vid2.mp4">
</video>
</div>
</html>
The videos show up correctly.
I want to add an overlay text (caption) on top of each video like:
"Video 1 – Greenery"
"Video 2 – Island"
How can I do this using Javascript alone without modifying the HTML?
If not overlay, how do I display caption right above or below each video.
I have tried this:
var vid = document.getElementById("vid-1");
vid.insertAdjacentHTML("aftereend","Video 1 - Greenery");
But the text "Video 1 – Greenery", appears on right side of video.
If it appeared directly above or below video that would work too.
2
Answers
Style is just for example purposes.
Naturallly better is to use file styles.
insertAdjacentHTML renders an Element, so if You put a raw text, then it creates a textNode.
Better to wrap it in some tag – then style has access to it.
using
${customStyle}
You make it easier to maintain.It’s easier to set dynamic elements with it’s inline styes than to operate on window stylesheets.
This solution makes styling Your text possible.
TL;DR:
<figcaption>
(and<figure>
).position: absolute
.We can map video IDs to captions. Then for all entries, we can create and insert the captions before their corresponding videos:
Note:
aria-labelledby
. (Captions labelling content is done implicitly when using<figcaption>
as below.)Without styling, the captions will come before their videos. To place them above their videos we need styling (CSS).
Placing elements above others can be achieved by taking them out of the flow, e.g. with
position: absolute
.We want to position the captions relative to the videos. But the captions are siblings and not children of the videos, which makes relative positioning more difficult.
We can wrap each caption and its video in another element, which will effectively represent the video. That way, the caption is a child of the "video" (the wrapper), which makes positioning it correctly easier:
There already exist elements for captions and the wrapper:
<figcaption>
and<figure>
. You should prefer these where applicable, e.g. here:Note: The
<figure>
element isdisplay: block
whereas<video>
isdisplay: inline
by default. The stylesheet should fix this inconsistency.