Created
August 9, 2023 17:51
-
-
Save sidisinsane/5654078312145723cc55602584c5fe55 to your computer and use it in GitHub Desktop.
Stops other media elements from playing when a media element starts playing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Stops other media elements from playing when a media element starts playing. | |
* | |
* @param {HTMLMediaElement[]} mediaElems - An array of HTML media elements. | |
* | |
* @example | |
* | |
* // Stop other media elements when one starts playing | |
* const allMediaElems = document.querySelectorAll("audio, video"); | |
* stopOtherMedia(allMediaElems); | |
*/ | |
function stopOtherMedia(mediaElems) { | |
Array.from(mediaElems).forEach((elem) => { | |
elem.addEventListener("playing", (event) => { | |
Array.from(mediaElems).forEach((elem) => { | |
if (elem !== event.target) { | |
elem.pause(); | |
elem.currentTime = 0; | |
} | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment