Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=yes" />
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>Use the Twitch JSON API</title>
</head>
<body>
    <div class="flex-container">
        <div id="offline">Offline</div>
        <div id="online">Online</div>
    </div>
    <div class="search-container">
        <div>
            <input type="text" placeholder="add streamer" />
            <p id="error"></p>
        </div>
        <div id="search">
            <img src="images/search.png" alt="search" />
        </div>
    </div>
    <div class="scene">
        <div class="carousel"></div>
    </div>
    <div class="carousel-options">
        <p>
            <button class="previous-button">Previous</button>
            <button class="next-button">Next</button>
        </p>
    </div>
  <a href="http://cselko.offyoucode.co.uk/fcc/take_home/twitch/" target="_blank">Click to open on new tab</a>
    <div id="tv">
        <div id="embedTwitchTV"></div>
    </div>
    <footer> &copy; Developed by Csaba. 2019
        <a href="https://www.freecodecamp.org/learn/coding-interview-prep/take-home-projects/use-the-twitch-json-api" target="_blank">
            <img src="images/fcc-logo-white.png" alt="FreeCodeCamp logo" />
        </a>
    </footer>
    <script src= 7"https://player.twitch.tv/js/embed/v1.js"></script>
    <script src="index.js"></script>
</body>    
</html>
<!--    
background: https://www.pexels.com/photo/blue-bright-clouds-cloudy-417122/
-->
              
            
!

CSS

              
                body {
    background-image: url(images/sky.jpeg);
    background-size: cover;
    background-repeat: no-repeat;
    box-sizing: border-box;
    text-align: center;
    min-height: 100vh;
}

/*  style switcher buttons  */
.flex-container {
    display: flex;
    justify-content: center;
    margin-top: -6px;
}
.flex-container > div {
    width: 50%;
    line-height: 25px;
}

.flex-container > div, button, input[type=text], #error {   
    border: 1px solid black;
    box-shadow: 2px 2px 2px 0px black;
}
.flex-container > div, button {
    background-color: aliceblue;
    cursor: pointer;
}

button { 
    width: 100px;
    height: 25px;
}

#offline:hover, #online:hover, button:hover {
    background-color: lightgrey;
}

#offline.active {
    background-color: darkred;
    color: aliceblue;
    box-shadow: none;
}

#online.active {
    background-color: chartreuse;
    color: black;
    box-shadow: none;
}

button:active {
    background-color: black;
    color: white;
}

/*  --------------------  style search    --------------------     */
.search-container {
	display: flex;
    justify-content: center;
}

input[type=text] {
    padding: 6px;
    margin-top: 8px;
    font-size: 17px;
    width: 0px;
    opacity: 0;
    transition: 1s;
}

.search-container img {
    width: 45px;
    transform: rotate(270deg);
    cursor: pointer;
}

#error {
	position: absolute;
    top: 30px;
    left: 50%;
    transform: translate(-50%);
    background-color: salmon;
    min-width: 210px;
    font-size: 18px;
    padding: 6px;
    font-weight: bold;
    transition: 0.7s;
    display: none;
    opacity: 0;
    z-index: 10;
    margin: 0 auto;
}
/*  --------------------  style carousel    --------------------     */
.scene {
    margin: -5px auto 40px;
	width: 210px;
    height: 140px;
    position: relative;
    perspective: 1000px;
}

.carousel {
	width: 100%;
	height: 100%;
    position: absolute;
    transform-style: preserve-3d;
    transform: translateZ(-288px);
    transition: transform 1s;
}

.carousel-cell {
	position: absolute;
    width: 190px;
    height: 120px;
    left: 10px;
    top: 10px;
/*    border: 2px solid black;*/
    line-height: 116px;
    transition: transform 1s, opacity 1s;
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
}

.close {
	position: absolute;
    font-size: 30px;
    top: -35px;
    right: 5px;
    color: grey;
}

.close:hover {
    font-size: 35px;
    color: red;
}

.carousel-cell h3 {
	opacity: 0.3;
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    font-weight: bold;
    margin-top: 80px;
    font-size: 25px;
}

/*  style off-line / online users:  */
.online h3 {
    color: chartreuse;
}

.offline h3 {
    color: darkred;
}

.carousel-options {
    position: relative;
    top: 0px;
    z-index: 2;
}

/*  --------------------    Style tv    --------------------    */
#tv {
    width: 528px;
    height: 297px;
    background-image: url(images/tv.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    padding-top: 11px;
    margin: 0 auto;
}

#embedTwitchTV {
    height: 230px;
    width: 390px;
    background-color: black;
    margin: 0 auto;
}
/*  --------------------    Style footer    --------------------    */
footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    --fccGreen: #eee;
    background-color: transparent;
    color: transparent;
    text-align:  left;
    padding: 8px;
    transition: background-color 0.8s;
}

footer img {
    width: 40px;
    margin: -10px 10px;
    float: right; 
}

footer:hover {
    --fccGreen: #006600;
    color: aliceblue;
    background-color: var(--fccGreen);
}

/*  --------------------    Style mobile    --------------------    */
@media (orientation: portrait) {
    .scene {
        margin: 150px auto;
        width: 210px;
        height: 140px;
        
    }
    
    .carousel-cell h3 {
        margin-top: 65px;
        font-size: 30px;
    }
    
    .offline h3 {
        text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
    }
    
    .carousel-options {
        position: relative;
        top: -225px;
        right: -49%;
        transform: rotate(90deg);
    }
    
    .carousel-options button {
        width: 28%;
        height: 25px;
    }
    
    #tv {
        width: 100%;
        margin-top: -50px;
        z-index: 500;
    }
              
            
!

JS

              
                "use strict";
const callAJAX = (props) => {
    const url = props.url,
          method = props.method || "GET",
          type = props.type || "JSON",
          header = props.header
    ;
    return new Promise(waitForResult => {
        const xhttp = new XMLHttpRequest();
        if (method === "GET") {
            xhttp.open("GET", url, true);
            for (const key in header) {
                xhttp.setRequestHeader(key, header[key]);
            }
            xhttp.send();
        } else {
            xhttp.open("POST", url, true);
            for (const key in header) {
                xhttp.setRequestHeader(key, header[key]);
            }
            xhttp.send(props.data);
        }
        xhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
//                console.log(this.response);
                type === "text"
                    ? waitForResult(this.response)
                    : waitForResult(JSON.parse(this.response))
                ;
            }
        };
    });
};

// get app access token

const AJAXProps = {
    url: "https://id.twitch.tv/oauth2/token?client_id=1g1x4wqwbye3jzo23y84h34bom5duw&client_secret=1xcgo8mlxte1zbllr9ngy1pq9hhclh&grant_type=client_credentials",
    method: "POST"
};

callAJAX(AJAXProps).then(response => {
    const accessToken = response.access_token;
    
    const AJAXProps = {
        url: "https://api.twitch.tv/helix/streams?first=20",
        header: {
            "client-ID": "1g1x4wqwbye3jzo23y84h34bom5duw",
            "Authorization": `Bearer ${accessToken}`
        }
    };

    // Remove duplicated values from an array:
    const uniqueArray = dirtyArray => dirtyArray.filter((value, index, array) => array.indexOf(value) === index);

    let users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "forsen", "storbeck", "pokimane", "habathcx", "RobotCaleb", "noobs2ninjas", "myth"];
    users = uniqueArray(users);

    const dom = {
        offline: document.getElementById("offline"),
        online: document.getElementById("online"),
        input: document.getElementsByTagName("input")[0],
        search: document.getElementById("search"),
        error: document.getElementById("error"),
        embedTwitchTV: document.getElementById("embedTwitchTV"),
        carousel: document.querySelector(".carousel"),
    },
          cellWidth = dom.carousel.offsetWidth,
          cellHeight = dom.carousel.offsetHeight
    ;

    let names = "",
        appendCells = "";
    ;
    for (let i = 0;  i < users.length; i++) {
        appendCells += `<div class="carousel-cell offline"></div>`;
        let name = users[i];
        !(names) 
            ? names += name
            : names += `&login=${name}`
        ;
    };
    dom.carousel.innerHTML = appendCells; 
    dom.cells = document.querySelectorAll(".carousel-cell");

    const showError = message => {
        // show error container:
        dom.error.innerHTML = message;
        dom.error.style.display = "block";
        dom.error.style.opacity = 1;
        // hide error container:
        setTimeout(() => {
            dom.error.innerHTML = ``;
            dom.error.style.display = "none";
            dom.error.style.opacity = 0;
        }, 3000);
    };

    const deleteUser = () => {
        const activeCell = dom.cells[selectedIndex];
    //    users.splice(selectedIndex, 1); // delete active user from the users array
        if (dom.cells.length > 1) {
            activeCell.remove();        
        } else   {
            showError("The last user cannot to delete.");
        }
        changeCarousel();
    };

    // ------------------ Twitch API -------------------
    // set stream:
    const setStream = (userName) =>{
        // change the name of opacity:
        dom.cells.forEach(cell => {
            cell.children[0].style = "opacity: 0.3";
            cell.children[0].firstElementChild.removeEventListener("click", deleteUser);
        });
        const carouselName = document.getElementById(userName).children[0];
        carouselName.style = "opacity: 1";

        // add event listener to delete streamer from the list:
        const close = document.getElementById(userName).children[0].firstElementChild;
        close.addEventListener("click", deleteUser);

        // embed stream:
        const options = {
            width: 390,
            height: 230,
            channel: userName
        };
        const player = new Twitch.Player("embedTwitchTV", options);
        player.setVolume(0.5);
        console.log(document.getElementsByTagName("iframe")[0]);
        document.getElementsByTagName("iframe")[0].setAttribute("sandbox", "allow-scripts allow-top-navigation");
    };
    // Get Users:
    AJAXProps.url = `https://api.twitch.tv/helix/users?login=${names}`;
    callAJAX(AJAXProps).then(allUser => {
        console.log("get User by login name:", allUser);
        // check if users now streaming:
        AJAXProps.url = `https://api.twitch.tv/helix/streams?first=20&login=${names}`.replace(/login/g, "user_login");
        // the names inconsistent, so have to work with user_id!!!:
        users.forEach((user, i) => {
            users[i] = allUser.data[i].id;
            // change background image
            dom.cells[i].style.backgroundImage = `url(${allUser.data[i].offline_image_url || allUser.data[i].profile_image_url})`;
            // display name:
            dom.cells[i].setAttribute("id", allUser.data[i].login);
            dom.cells[i].innerHTML = `
                <h3>${allUser.data[i].display_name}
                    <span class="close">&times;</span>
                </h3>
            `;
        });
        callAJAX(AJAXProps).then(onlineUsers => {
            console.log("check if the given users now streaming", onlineUsers);
            if (onlineUsers.data.length) {
                onlineUsers.data.forEach(onlineUserData => {
                    // update the cell of online users:
                    const userCell = users.indexOf(onlineUserData.user_id);
                    if (userCell > -1) {
                        dom.cells[userCell].style.backgroundImage = `url(${allUser.data[userCell].profile_image_url})`;
                        // change the offline statut to online:
                        dom.cells[userCell].className = "carousel-cell online";
                    }
                });
            }
            setStream(allUser.data[0].login);
            console.log(document.getElementsByTagName("iframe"));
        });
    });

    // ----------------- offline-online switcher ------------------
    // add event listener to the buttons:
    let mode = "carousel-cell";
    const switcher = () => {
        if (event.target.id === "offline") {
            if (dom.offline.classList.value === "") {
                dom.offline.classList.add("active");
                dom.online.classList.remove("active");
                mode = "offline";
            } else {
                dom.offline.classList.remove("active");
                mode = "carousel-cell";
            }
        } else {
            if (dom.online.classList.value === "") {
                dom.online.classList.add("active");
                dom.offline.classList.remove("active");
                mode = "online";
            } else {
                dom.online.classList.remove("active");
                mode = "carousel-cell";
            }
        }
        changeCarousel();
    };

    dom.offline.addEventListener("click", switcher);
    dom.online.addEventListener("click", switcher);

    // ----------------- Search  ------------------
    let inputOpen = false;
    const searchUser = () => {
        if (!(inputOpen)) {
            inputOpen = true
            dom.input.style.width = "200px";
            dom.input.style.opacity = 1;
        } else {
            inputOpen = false;
            dom.input.style.width = "0px";
            dom.input.style.opacity = 0;
            const newUser = dom.input.value;
            dom.input.value = ""; 
            AJAXProps.url = `https://api.twitch.tv/helix/users?login=${newUser}`;
            callAJAX(AJAXProps).then(user => {
                if (user.data.length) {
                    if (document.getElementById(user.data[0].login)) return showError("This streamer already added to the list.");
                    AJAXProps.url = `https://api.twitch.tv/helix/streams?user_login=${user.data[0].login}`;
                    let newNode = `<div id="${user.data[0].login}" class="carousel-cell `;
                    callAJAX(AJAXProps).then(onlineUser => {
                        if (onlineUser.data.length) {
                            newNode += ` online" style="background-image: url(${user.data[0].profile_image_url}" </div>`;
                        } else {
                            newNode += ` offline" style="background-image: url(${user.data[0].offline_image_url || user.data[0].profile_image_url}"</div>`;
                        }
                        newNode += `
                            <h3>${user.data[0].display_name}
                                <span class="close">&times;</span>
                            </h3>
                        `;
                        dom.carousel.innerHTML += newNode;
                        changeCarousel();
                    });
                } else {
                    // show error container:
                    showError(`Unknown user: ${newUser}`);
                }
            });
        }


    };
    dom.search.addEventListener("click", searchUser);

    // ----------------- Carousel ------------------
    let selectedIndex = 0,
        isHorizontal = true,
        cellCount,
        rotateFn = isHorizontal ? "rotateY" : "rotateX",
        radius,
        theta
    ;
    const rotateCarousel = () => {
        const angle = theta * selectedIndex * -1;
        dom.carousel.style.transform = `translateZ(${-radius}px) ${rotateFn}(${angle}deg)`;
        if (selectedIndex < 0) selectedIndex = dom.cells.length - 1;
        if (selectedIndex === dom.cells.length) selectedIndex = 0;
        const userName = dom.cells[selectedIndex].getAttribute("id");
        if (userName) {
            dom.embedTwitchTV.innerHTML = "";
            setStream(userName);
        }
    };

    const prevButton = document.querySelector(".previous-button");
    prevButton.addEventListener("click", () => {
        selectedIndex --;
        rotateCarousel();
    });

    const nextButton = document.querySelector(".next-button");
    nextButton.addEventListener("click", () => {
        selectedIndex ++;
        rotateCarousel();
    });

    const changeCarousel = () => {

        const showCell = (cell, i) => {
            cell.style.opacity = 1;
            const cellAngle = theta * i;
            cell.style.transform = `${rotateFn}(${cellAngle}deg) translateZ(${radius}px)`;
        };
        const hideCell = (cell, i) => {
            cell.style.opacity = 0;
            cell.style.transform = "none";
        };
        for (let i = 0; i < dom.cells.length; i++) {
            const cell = dom.cells[i];
            hideCell(cell, i);
        }

        dom.cells = document.querySelectorAll(`.${mode}`);
        if (selectedIndex >= dom.cells.length) selectedIndex = dom.cells.length - 1; // bug fixed 

        cellCount = dom.cells.length;
        theta = 360 / cellCount;
        const cellSize = isHorizontal ? cellWidth : cellHeight;
        radius = Math.round((cellSize / 2) / Math.tan(Math.PI / cellCount));
        if (radius < 0) {
            radius = 288;
        }
        for (let i = 0; i < dom.cells.length; i++) {
            const cell = dom.cells[i];
            showCell(cell, i);
        }
        rotateCarousel();
    };

    const onOrientationChange = () => {
        isHorizontal = window.innerHeight < window.innerWidth;
        rotateFn = isHorizontal ? "rotateY" : "rotateX";
        changeCarousel();
    };

    window.addEventListener("resize", onOrientationChange);

    // set initials
    onOrientationChange();
});

              
            
!
999px

Console