skip to Main Content

I am trying create a loop that would create a video thumbnail that contains the video title.

I currently have the function set up to get the IDs and I can get the loop to generate the thumbnail and link, how would I write out the array or function to include the title?

This is my current layout.

var Ids = "id1,id2,id3";

 if (typeof Ids === 'undefined') { Ids = ""; }
 var vIds = Ids.split(",");

$.each(vIds, function(index,value) {

 $('.vrow').append('<button type="button" class="btn btn-link col-lg-2 col-md-2 col-sm-2 col-xs-6 vid vid'+index+'"><img src="https://img.youtube.com/vi/'+value+'/mqdefault.jpg" alt="" /><span><i class="fa fa-play"></i></span></button>');
 });

I did try to use a separate array for the title, but it only created more loops and it did not render the YT ID.

Would it be possible to use the array for both the ID and Title? If so, how would I be able to map title value? Would this be considered as a multidimensional array?

var Ids = "id1,title1,id2,title2";

2

Answers


  1. First, the IDs must not be spaced with , otherwise you’ll get id2 instead of id2:

    var Ids = "id1,id2,id3";
    

    To insert also the title you can use another different character as delimiter, for example:

    var iDsWithTitle = "id1|title1,id2|title2,id3|title3";
    

    Be aware that the title may contains ,, so you should chose another delimiter such as |.

    A better method is by using a json string to store those data and then convert it to an object that you’ll cycle.

    Login or Signup to reply.
  2. You could create an array objects like below. Then each object would contain the video’s information. Then simply loop through the array and reference the video’s information.

    let videos = [
    {"id": "id1","title": "Video Title 1"},
    {"id": "id2","title": "Video Title 2"},
    {"id": "id3","title": "Video Title 3"},
    {"id": "id4","title": "Video Title 4"}
    ];
    
    $.each(videos, function(index,video) {
      $('.vrow').append('<button type="button" class="btn btn-link col-lg-2 col-md-2 col-sm-2 col-xs-6 vid vid' + video.id + '"><img src="https://img.youtube.com/vi/' + video.id + '/mqdefault.jpg" alt="" /><span><i class="fa fa-play"></i></span></button>');
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="vrow"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search