Hero video: try sound on load, fall back to muted, first tap or key anywhere turns sound on and restarts the clip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-01 05:41:14 -05:00
parent 0325b87e0b
commit 5d21dfd507
+14 -4
View File
@@ -51,14 +51,24 @@ p{color:var(--muted);margin:0 auto 14px;max-width:52ch}
</main>
<script>
(function () {
var v = document.getElementById('hero'), b = document.getElementById('sound');
var v = document.getElementById('hero'), b = document.getElementById('sound'), touched = false;
function label() { b.textContent = v.muted ? '🔇 Tap for sound' : '🔊 Sound on'; b.setAttribute('aria-pressed', String(!v.muted)); }
// browsers only allow sound after the visitor interacts, so: try with sound, fall back to muted,
// and the first tap or key anywhere on the page turns the sound on and restarts the clip
v.muted = false;
v.play().then(label).catch(function () { v.muted = true; label(); v.play().catch(function () {}); });
function firstTouch(e) {
if (touched) return; touched = true;
document.removeEventListener('pointerdown', firstTouch, true); document.removeEventListener('keydown', firstTouch, true);
if (e && e.target === b) return; // the button handles itself
if (v.muted) { v.muted = false; v.currentTime = 0; v.play().catch(function () {}); label(); }
}
document.addEventListener('pointerdown', firstTouch, true); document.addEventListener('keydown', firstTouch, true);
b.addEventListener('click', function () {
v.muted = !v.muted;
if (!v.muted) { v.currentTime = 0; v.play().catch(function () {}); }
b.textContent = v.muted ? '🔇 Tap for sound' : '🔊 Sound on';
b.setAttribute('aria-pressed', String(!v.muted));
label();
});
v.play().catch(function () {}); // some phones need a nudge even for muted autoplay
})();
</script>
</body>