Skip to content

Instantly share code, notes, and snippets.

@capperstrnd
Last active March 11, 2022 21:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save capperstrnd/f5323765e3358ae27d4a97eb2d63aa3c to your computer and use it in GitHub Desktop.
Save capperstrnd/f5323765e3358ae27d4a97eb2d63aa3c to your computer and use it in GitHub Desktop.
A simple script for embedding Twitch stream only when the channel is live, otherwise it is hidden.
<html>
<head>
<style>
.hide { display:none; }
/* Optional: The following css just makes sure the twitch video stays responsive */
#twitch {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
}
#twitch object, #twitch iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script src= "https://player.twitch.tv/js/embed/v1.js"></script>
<div id="twitch" class="hide">
</div>
<script type="text/javascript">
var player = new Twitch.Player("twitch", options);
var options = {
channel: "USERNAME", // TODO: Change this to the streams username you want to embed
width: 640,
height: 360,
};
player.addEventListener(Twitch.Player.READY, initiate)
function initiate() {
player.addEventListener(Twitch.Player.ONLINE, handleOnline);
player.addEventListener(Twitch.Player.OFFLINE, handleOffline);
player.removeEventListener(Twitch.Player.READY, initiate);
}
function handleOnline() {
document.getElementById("twitch").classList.remove('hide');
player.removeEventListener(Twitch.Player.ONLINE, handleOnline);
player.addEventListener(Twitch.Player.OFFLINE, handleOffline);
player.setMuted(false);
}
function handleOffline() {
document.getElementById("twitch").classList.add('hide');
player.removeEventListener(Twitch.Player.OFFLINE, handleOffline);
player.addEventListener(Twitch.Player.ONLINE, handleOnline);
player.setMuted(true);
}
</script>
</body>
</html>
@kyrg22
Copy link

kyrg22 commented Jan 26, 2022

How can I place multiple streams? can i add the chat?

@seanmcnally98
Copy link

You can add the chat, I made my own version that includes it: https://gist.github.com/seanmcnally98/093880d7b0f0d476ab150183db991ed3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment