I have a video player which changes its parent based on media queries, i.e. in “small” mode it’s in one part of the layout, and in “large” mode it’s in another. To make sure the video keeps playing across resolution changes, I explicitly re-parent the video player rather than, say, creating a new one, hiding/showing two different players, etc.
I currently do this with Javascript, but I was wondering: can this can be accomplished with alpine’s x-teleport
?
I can think of two broad approaches to try. First, can I dynamically update the x-teleport
attribute value to point to different elements as the resolution changes? Some quick experimentation makes me think this isn’t possible, but I’m still relatively new at alpines and may have just “done it wrong”.
Second, can I leave the x-teleport
attribute at one value, but change the attributes on the target elements as the resolution changes? I tried pointing x-teleport
at “#video-container”, and I then modulated the id
attribute on two different elements to try getting the effect I want. This did not seem to work.
Should either of these approaches work in principle? Is there another way perhaps to accomplish what I’m looking for?
Edit:
Here’s a minimal example which I think should work, but which doesn’t:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>
<body>
<div id="small">small</div>
<div id="normal">normal</div>
<div x-data="container">
<template :x-teleport='normal ? "#normal" : "#small"'>
<div>teleported</div>
</template>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('container', () => ({
normal: false,
init() {
let mql = window.matchMedia("(min-width: 640px)");
mql.addListener((e) => {
this.normal = e.matches;
});
}
}));
});
</script>
</div>
</body>
</html>
The ‘teleported’ div
should get moved between #small
and #normal
based on media queries. Can anyone see why this won’t work?