Video results on Recipe Finder are cards with a thumbnail, a title and a view count. Hovering a card for a moment mounts a muted YouTube player under the thumbnail, so you can see the dish being prepared before you decide to open it. Moving the pointer away removes the preview.
Clicking the card opens the video on YouTube in a new tab.
Three requirements shaped the design. The preview must never start by accident. It must not load a third-party frame until someone actually wants it. And it must respect visitors who have asked for less motion. Each requirement maps to a part of the code below.
The pieces
The feature is split into small parts, each doing one job:
Piece Job RecipeVideoCard.vue The card. Forwards pointer events, shows the loading bar and the play icon, and opens the video on click. RecipeVideoPreview.vue The layer over the thumbnail: the cropped frame, the mute button and the progress bar. useVideoPreview.ts The state machine: the dwell timer, the embed address, the messages from the player and the cleanup. utils/videoPreview.ts Pure helpers: build the embed address, read a player message, compute the progress. constants/videoPreview.ts Every delay, origin and player setting, in one file. shared/AppCardLoadingBar.vue The thin bar along the top edge that shows a preview is on its way.
1. Start only when someone is resting on the card
A pointer that crosses a card on its way somewhere else should not start a video. The preview therefore waits 400 ms after the pointer enters (DWELL_DELAY_MS). If the pointer leaves during that wait, the timer is cleared and nothing loads.
Before the timer is even set, the code checks whether a preview is allowed at all. Only a device with a real pointer can rest on a card, so phones and tablets never get one. Visitors who prefer reduced motion never get one either.
ts
function canPreview(): boolean {
const videoId = getVideoId();
return (
isEnabled() &&
!isNilOrEmpty(videoId) &&
!unavailableVideoIds.has(videoId) &&
window.matchMedia(VIDEO_PREVIEW.HOVER_MEDIA_QUERY).matches &&
!hasReducedMotionPreference()
);
}
function onPointerEnter() {
const isPreviewStarted =
dwellTimer !== undefined || !isNilOrEmpty(embedUrl.value);
if (isPreviewStarted || !canPreview()) {
return;
}
isPreviewLoading.value = true;
dwellTimer = setTimeout(startPreview, VIDEO_PREVIEW.DWELL_DELAY_MS);
}
HOVER_MEDIA_QUERY is (hover: hover) and (pointer: fine). A video that could not play once, because its owner blocks embedding or because it has been removed, is remembered in a set for the rest of the visit. That card keeps its thumbnail and does not try again.
2. An embed built from one list of settings
The preview is a YouTube embed on youtube-nocookie.com, the privacy-enhanced domain. Its address comes from a single list of player settings: muted and autoplaying, with every control switched off, no keyboard shortcuts, no fullscreen, no annotations, and related videos limited to the same channel (rel=0). Two settings matter for the code that follows. enablejsapi=1 lets the page drive the player, and origin names the only page the player should answer to.
ts
export function buildVideoPreviewUrl(
videoId: string,
pageOrigin: string
): string {
const params = new URLSearchParams({
...VIDEO_PREVIEW_PLAYER_PARAMS,
origin: pageOrigin,
});
return `${VIDEO_PREVIEW.ORIGIN}${VIDEO_PREVIEW.EMBED_PATH}${encodeURIComponent(videoId)}?${params.toString()}`;
}
The frame is created only when the dwell timer fires, so a card that is never rested on costs nothing. YouTube also refuses an embed that arrives without a referrer, which is why the frame sends strict-origin-when-cross-origin.
3. Talking to the player with postMessage
The player understands a message protocol. The page posts JSON strings to the frame, and the player posts JSON back. Three rules govern the conversation.
The handshake. The player answers only once it has started. So when the frame loads, the page sends a listening message every 250 ms until the player replies. Only then does it subscribe to state changes and errors.
ts
function onFrameLoad(event: Event) {
const frame = event.target;
if (!(frame instanceof HTMLIFrameElement) || !frame.contentWindow) {
return;
}
playerWindow = frame.contentWindow;
stopHandshake();
handshakeTimer = setInterval(
() => sendToPlayer(VIDEO_PREVIEW_PLAYER_EVENTS.LISTENING),
VIDEO_PREVIEW.HANDSHAKE_INTERVAL_MS
);
}
Every incoming message is checked. The origin must be the youtube-nocookie domain, and the source must be the window of our own frame. Anything else on the page is ignored.
ts
function handleMessage(event: MessageEvent) {
if (
event.origin !== VIDEO_PREVIEW.ORIGIN ||
event.source !== playerWindow
) {
return;
}
const message = parseVideoPreviewMessage(event.data);
// ...
}
The player reports what changed. Each message carries only the fields that changed: currentTime, duration or playerState. Playing, paused and ended are handled as states, and an error marks the video as unavailable.
4. Hiding the player's own title and buttons
For the first three seconds of every video, the player shows its own title, its links and a pause button, and then fades them out. The API has no switch to turn that off, and we cannot change the player. So we crop it instead, and keep the card's overlay up for 3.4 seconds to cover the fade.
The frame is sized like object-fit: cover for 16:9 video, and it is 160 px taller than the video at the top and at the bottom. The player's title and links therefore fall outside the visible area. The sizing uses container query units, so it follows the card at every width.
html
<div class="absolute inset-0 overflow-hidden [container-type:size]">
<iframe
class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2
w-[max(100cqw,177.78cqh)]
h-[calc(max(56.25cqw,100cqh)_+_320px)] max-w-none border-0"
/>
</div>
The pause button still sits under the card's play icon for those first seconds. While the preview plays, a black disc sits behind the icon, so it covers the player's pause button. When the overlay timer ends, the icon fades out.
ts
isPlayerOverlayShown.value = true;
overlayTimer = setTimeout(() => {
isPlayerOverlayShown.value = false;
}, VIDEO_PREVIEW.PLAYER_OVERLAY_MS);
5. Sound that behaves like YouTube
The mute choice is one module-level value shared by every card. Unmute one preview and the next one plays with sound too, for the rest of the visit, as on YouTube.
Browsers block sound until the visitor has interacted with the page. When the player reports that it paused while we had asked for sound, the preview switches to muted and plays again, so it never sits frozen.
ts
if (state === VIDEO_PREVIEW_PLAYER_STATES.PAUSED && !isMuted.value) {
// The browser refused to play with sound, so the preview carries on muted.
isMuted.value = true;
sendCommand(VIDEO_PREVIEW_PLAYER_COMMANDS.MUTE);
sendCommand(VIDEO_PREVIEW_PLAYER_COMMANDS.PLAY);
return;
}
A small mute button sits at the top right of the preview. Its click stops propagation, so it does not open the video behind it.
6. Progress, countdown and a loading signal
Three small signals show the visitor what is happening. As soon as the pointer enters, a primary-coloured indeterminate bar runs along the card's top edge. While the preview plays, the duration badge counts down the seconds that remain, and a 3 px bar along the bottom of the preview fills.
The progress calculation is a pure function. It clamps the result between 0 and 100, and it returns 0 while the length of the video is still unknown.
ts
export function getVideoPreviewProgress(
currentTime: number,
duration: number
): number {
if (duration <= 0) {
return 0;
}
return Math.min(Math.max((currentTime / duration) * 100, 0), 100);
}
7. Cleanup, failures and the click
A preview must never outlive its reason to exist. One function, stopPreview, clears both timers and the handshake, removes the message listener and resets every piece of state. It runs in four places: when the pointer leaves, when the component unmounts, when the card now shows a different video, and when the visitor clicks the card, because the video then opens in its own tab.
ts
// Lifecycle Hooks
onScopeDispose(stopPreview);
// Watchers
watch(getVideoId, stopPreview);
If the player reports an error, the video is added to the unavailable set, and that card keeps its thumbnail for the rest of the visit.
What we learned
Wait before you start. A 400 ms dwell separates a deliberate pause from a pointer passing over.
Check who is asking. The pointer type, reduced motion, the message origin and the message source each decide something.
Create the frame only when it is needed. Nothing loads until the dwell has passed.
Crop what you cannot configure. The player's title and pause button sit outside the visible area.
Remember failures for the visit. A video that cannot play keeps its thumbnail, and the page does not retry it.
Keep the numbers in one file. Every delay and setting lives in constants/videoPreview.ts, so tuning the feel means editing one place.
Try it
Open recipe-finder.org, search for a dish, switch to the cooking videos and rest your pointer on a card for a moment. On a phone there is no preview, so tap the card to open the video on YouTube.