2

I want to put information about video in #t1, #t2 and #t3, but everything is placed in #t3. Where is the mistake in the code?

  $(function(){
        for (var i = 1; i < 4; i++) {
            var box = "#t" + i;
            var id = "dQw4w9WgXcQ";
          
            var img = "<img src='https://img.youtube.com/vi/" + id + "/default.jpg'>";
            console.log(i);

            $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id +  '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {

                $(box).prepend("viewCount: " + data.items[ 0 ].statistics.viewCount);


            });
            $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
                $(box).prepend("<h3>" + "Title" + data.items[0].snippet.title + "</h3>");
                $(box).prepend("<h3>" + "Channel title" + data.items[0].snippet.channelTitle + "</h3>");
                $(box).prepend(img);
            });
        }
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="t1"></div>
<div id="t2"></div>
<div id="t3"></div>

1
  • Look up how closures work in JavaScript! Your calls to $.getJSON() work asynchronously, the value for box is #t3 by the time the callback is executed! Commented Apr 15, 2016 at 12:12

2 Answers 2

3

Closures... wrap everything in a closure which would create a new scope for each iteration.

$(function(){      
        for (var i = 1; i < 4; i++) {
          (function(i)
            var box = "#t" + i;
            var id = "dQw4w9WgXcQ";

            var img = "<img src='https://img.youtube.com/vi/" + id + "/default.jpg'>";
            console.log(i);

            $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id +  '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {

                $(box).prepend("viewCount: " + data.items[ 0 ].statistics.viewCount);


            });
            $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
                $(box).prepend("<h3>" + "Title" + data.items[0].snippet.title + "</h3>");
                $(box).prepend("<h3>" + "Channel title" + data.items[0].snippet.channelTitle + "</h3>");
                $(box).prepend(img);
            });
        }
       })(i);
    });
Sign up to request clarification or add additional context in comments.

Comments

1

$.getJSON is asynchronous, handler will be invoked when response is received. But for-loop will not wait for handler to be called!

Create a inner-function and pass value of i as argument as value of i will be persistent for the inner-function.

$(function() {
  for (var i = 1; i < 4; i++) {
    var tobeCalled = function(i) {
      var box = "#t" + i;
      var id = "dQw4w9WgXcQ";
      var img = "<img src='https://img.youtube.com/vi/" + id + "/default.jpg'>";
      $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
        $(box).prepend("viewCount: " + data.items[0].statistics.viewCount);
      });
      $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=snippet&id=' + id + '&key=AIzaSyBlYMwv6QQ9x3r1ACVt1ZeyiRXiaGeKOBU', function(data) {
        $(box).prepend("<h3>" + "Title" + data.items[0].snippet.title + "</h3>");
        $(box).prepend("<h3>" + "Channel title" + data.items[0].snippet.channelTitle + "</h3>");
        $(box).prepend(img);
      });
    }
    tobeCalled(i);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="t1">
  <h2>1</h2>
</div>
<div id="t2">
  <h2>2</h2>
</div>
<div id="t3">
  <h2>3</h2>
</div>

1 Comment

I'm glad it helped! Happy Coding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.