jqueryhtmlajaxyoutube

Getting formatted Youtube Description (With line breaks and hyperlinks)


I'm wondering how I can pull a YouTube description from a given video whilst maintaining the formatting. I have successfully managed to get the description/title/thumbnail of the video, I just can't seem to keep the HTML formatting in the description. Whenever I put it into a div, it becomes one big clump of plain text.

My Code is as follows:

 var json = (function () {
     var json = null;
     $.ajax({
         'async': false,
         'global': false,
         'url': youTubeURL,
         'dataType': "json",
         'success': function (data) {
             json = data;
         }
     });
     return json;
 })();

Afterwards, I get the description and title like this:

 var desc = json.entry.media$group.media$description.$t;
 var title = json.entry.title.$t;

This is all well and good. However, when I go to put it in a div, like this:

 $('#video_desc').html('<h1>' + title + '</h1><p>' + desc + '</p>');

The description then shows up as one big block of text, where there should be line breaks and links. The weird thing is that when I do an alert or console.log of the description, it shows the correct formatting...

I'm sure it's something small I'm missing, but any help would be great, cheers!


Solution

  • For the line formatting, you can use:

    p{
      white-space: pre-line;
    }
    

    That will keep the formatting, but the rest is coming in as a string (call $.type(var) to see) so the links and any other HTML formatting would not carry over. My suggestion would be to find and replace the links for actual clickable ones. You can look into a URL library to help with this.

    FIDDLE