Skip to content

Instantly share code, notes, and snippets.

@sidisinsane
Created August 9, 2023 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidisinsane/5654078312145723cc55602584c5fe55 to your computer and use it in GitHub Desktop.
Save sidisinsane/5654078312145723cc55602584c5fe55 to your computer and use it in GitHub Desktop.
Stops other media elements from playing when a media element starts playing.
/**
* 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