Deise
Deise

Reputation: 51

Close <ul> each 8 <li>

I don't know how to close the element <ul> each 8 elements <li>. Someone can help me?

$.getJSON('https://www.googleapis.com/youtube/v3/search?key=AIzaSyDwHNKX0Ti4HYrJZ9Mf-mMIZxVU5JwiLVI&channelId=UCxRGbboDO9bCYd651YpIZuw&part=snippet,id&order=date&maxResults=50',
  function(data){
    var x = 0;
    var breakList = '';

    $.each(data.items, function(i,item){
      x++;

      if(x == 8){ //break ul if is 8
        x =0;
        breakList = 'break';
      }

      $('ul').append('<li class='+breakList+'>' + item.id.videoId + '</li>');

      breakList = '';
    });     

});

I tried break <ul> in the code but i can't.

Upvotes: 0

Views: 60

Answers (2)

guest271314
guest271314

Reputation: 1

You could use Array.prototype.slice() to copy data array; while loop containing Array.prototype.splice() with parameters 0, 8 to remove indexes between 0 and 8 while items remain in copied array

var data = $.map(Array(27), function(item, index) {
  return {"id":{"videoId":index}}
});

var copy = data.slice(0);

while (copy.length) {
  var curr = copy.splice(0, 8);
  var ul = $("<ul>", {css:{border:"2px solid olive"}});
  curr.forEach(function(item) {
    ul.append($("<li>", {
      html: item.id.videoId
    }))
  });
  $("body").append(ul);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Upvotes: 0

ak_
ak_

Reputation: 2815

You can use the % operator to create a new list every 8 items.

Something like this would work:

$.getJSON('https://www.googleapis.com/youtube/v3/search?key=AIzaSyDwHNKX0Ti4HYrJZ9Mf-mMIZxVU5JwiLVI&channelId=UCxRGbboDO9bCYd651YpIZuw&part=snippet,id&order=date&maxResults=50',
function(data){
var counter = 0;
$.each(data.items, function(i,item){
    if(i % 8 == 0) {
    counter++;
    $('#youTubeContainer').append('<ul id="list'+counter+'"></ul>');
}
  $('ul#list'+counter).append('<li>' + item.id.videoId + '</li>');

});     

});

Also, you probably want to give your list an ID and append the results to a specific ID.

See a working example here: https://jsfiddle.net/aghzznwx/2/

Hope that helps!

Upvotes: 1

Related Questions