Parsing JSON multiple times to extract data on the top 10 games from Twitch's API

Hey there! I have a little coding challenge for you. The current code below is only fetching the first channel from the JSON. My goal is to fetch all the streams and display them in a grid format with three streams per row. Can you help me achieve this? (Bonus question: How can I format all the fetched streams into a nice row-per-row grid which features three streams in each row)

<script>
     var twitchApi = "https://api.twitch.tv/kraken/streams";
     $.getJSON(twitchApi, function (json) {
     var streamGame = json.streams[0].game;
     var streamThumb = json.streams[0].preview;
     var streamVideo = json.streams[0].name;
     $('#twitch').append('<li><iframe src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe></li>');
    }
   );
</script>

On top of that, I need assistance with creating a script that fetches the top 10 games from a JSON. Check out the link here: . The process should be similar to the one above, but I'm hitting a mental block and could use your expertise to get this done.

Answer №1

By combining loops and inline-block elements, you can efficiently complete tasks. In this example, I utilized jQuery to organize rows of three cells each.

var twitchApi = "https://api.twitch.tv/kraken/streams";                                                                                                                          
$.getJSON(twitchApi, function (json) {
    var streamRow = $("<div class='stream-row'></div>").appendTo("#twitch"); // Creating the first row.
    var streamCell;
    var streamVideo;
    for (var i = 0; i < json.streams.length; i++)
    {
        if (i % 3 == 0 && i > 0)
        {
            // Start a new row every third iteration.
            streamRow = $("<div class='stream-row'></div>");
            $("#twitch").append(streamRow);
        }
        // Generate a cell with a video and include it in the row.
        streamVideo = json.streams[i].channel.name;
        streamCell = $("<div>", {
            css: {
                "class": "stream-cell",
                "display": "inline-block"
            }
        });
        streamCell.append('<iframe src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
        streamRow.append(streamCell);
    }
});

For the top ten feature, I implemented another loop. Since the API already provides data for 10 games, I used the length property instead of inputting a hardcoded number.

var twitchApi = "https://api.twitch.tv/kraken/games/top";                                                                                                                        
$.getJSON(twitchApi, function (json) {
    for (var i = 0; i < json.top.length; i++)
    {
        // Utilize the information from the JSON as needed.
        console.log(json.top[i].game.name)
    }
});

Answer №2

To simultaneously fetch multiple streams with the same data, you can utilize a for loop.

I corrected your streamVideo variable by adding ".channel" before ".name" (I recommend using a JSON viewer for a clearer understanding of the structure, such as Online JSON Viewer)

I also updated the script to display 10 iframes (I used the embed code from Twitch as your embed was too small).

For the styling, I suggest setting a 30% width for each iframe so that they align in rows of 3, with any remaining iframes in the bottom row.

var twitchApi = "https://api.twitch.tv/kraken/streams";
$.getJSON(twitchApi, function(json) {
  for (i = 0; i < 10; i++) {
    var streamGame = json.streams[i].game;
    var streamThumb = json.streams[i].preview;
    var streamVideo = json.streams[i].channel.name;
    $('#twitch').append('<li><iframe src="https://player.twitch.tv/?channel=' + streamVideo + '" frameborder="0" scrolling="no" height="378" width="620"></iframe><li>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to make an AngularJS Expression show an empty value

Consider the following HTML snippet: <p>{{ booleanVariable ? "The variable is true!" : "" }}</p> In case 'booleanVariable' evaluates to false, the expression should display nothing and the <p></p> tags should not be show ...

Is it possible to manipulate an image tag's image using only CSS?

Is it possible to hide an image from the src attribute of an <img> tag and instead set a background image on the tag using CSS? One idea could be adjusting the positioning or text-indent of the actual image to move it out of view, and then applying ...

Mobile-formatted inline Bootstrap

Using bootstrap and seeking to have elm1, elm2, and elm3 displayed inline on mobile devices? Take a look at the code snippet below: <div class="container-fluid"> <div class="form-group"> <label class="control-label col-sm ...

What is the reason behind TypeScript enclosing a class within an IIFE (Immediately Invoked Function

Behold the mighty TypeScript class: class Saluter { public static what(): string { return "Greater"; } public target: string; constructor(target: string) { this.target = target; } public salute(): string { ...

Guide on presenting an image retrieved from a database with ajax

I am currently developing a straightforward mobile application that utilizes a database to store various types of content, including images. I have implemented ajax requests to retrieve this information and display it within the app. However, I am encounte ...

How can I place text on top of an image with a filter using Bootstrap?

I am facing a challenge of overlaying text on an image with a tinted background color and opacity. While working with Bootstrap 4, I suspect that some classes might be conflicting with each other. This is my current setup: Index.cshtml: <div class=" ...

The animation of the splash screen in Angular is quite jarring and lacks fluidity

I am experiencing some issues with my angular splash screen animation. It works perfectly when there is no activity in the background, but when I simulate a real-life application scenario, the animation becomes stuttered, choppy, or sometimes does not anim ...

Combining D3.js tooltip positioning with CSS overflow styling

I am encountering an issue with displaying tooltips in D3 when combined with CSS overflow. Is there a solution available for this particular problem? CSS code: #chart1 { overflow-x: auto; overflow-y: hidden; max-width: 800px; max-height: 22 ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

An easy way to place text along the border of an input field in a React JS application using CSS

I am struggling to figure out how to create an input box with text on the border like the one shown in the image below using CSS. I have searched extensively but have not been able to find any solutions to achieve this effect. I attempted using <input&g ...

Making an asynchronous request from jQuery to a Slim Framework API endpoint

I'm currently working on incorporating Slim into my project and I'm facing some challenges with setting up the AJAX call correctly: $.ajax({ url: "/api/addresses/", type: 'POST', contentType: 'application/j ...

Troubleshooting Problems with CSS Span Placement

Challenges with Span Positioning in CSS Currently, I am encountering difficulties while working on the index.html.erb file for an example Rails website. Below is a snippet of the HTML code I am struggling with (please note that this is simply a fabricated ...

Photographs housed within a pop-up window

My popover is causing me some trouble: I've got a popover that displays PHP-generated content without a fixed height, and I want to add an image inside it. The tooltip appears over my element like this: The problem is that if the image isn't pr ...

Turning simple text into JSON format

Beginner JS coder here, currently developing a program that pings IoT devices on a network and outputs a true or false value based on the success of the ping. Everything is functioning well so far, but I'm now attempting to extract specific propertie ...

Maximizing Efficiency with the jQuery setInterval() Function: Optimizing the Initial Loop

I have implemented the setInterval function to create a loop featuring a Text Slider animation: Visit this FIDDLE for a live demo. The HTML structure is as follows: <div id="Slider"> <ul> <li class="active">Sempe ...

Get rid of the add to cart message and modify the button that says "add to cart" on Woocommerce

How can I modify the shopping cart page to remove the "has been added to your cart" text and replace the quantity and add to cart button with a custom button (my image)? Here is an example of what I am trying to achieve: This is the current state of the p ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...

Node.js encounter an error while processing an Ajax request

Running a node.js server on port 3000, my index.html file sends an Ajax request to a apache2 server on port 80 in order to retrieve the current cookie on the site. Despite seeing the cookie on the browser, no cookie response is received. The Ajax request i ...

Leverage the power of Next.js to dynamically render a specific section of an HTML webpage

I want to incorporate Next.js into a specific section of my website, while the rest of the site is built using different frameworks that are not even based on React. I aim to use Next.js within a <div id="nextjs_div">...</div> element ...

Starting jQuery on embedded websites

I developed a platform that relies on JavaScript. Users of my platform are required to paste a code similar to Google Analytics, which automatically deploys a custom set of JavaScript functions along with the latest jQuery 1.9 through Google. The issue I ...