jqueryajaxapi-linkpreview

How to make a preview box using LinkPreview API?


Like below image link preview shown, it's an image of what I expect in same way as soon as user inserts a link in the textarea.

From link preview site, I am getting image,url,description of site in console window, but I want to display inside a <div> tag.

link preview image of website

html:

<div class="show_lnk"></div>

 <textarea class="form-control" placeholder=""  id="url" name="user_status"></textarea>     

jquery:

jQuery("textarea[name*='user_status']").blur(function () {
    var target = jQuery(this).val();
    $.ajax({
        url: "https://api.linkpreview.net",
        dataType: 'jsonp',
        data: {q: target, key: '5a2e292e7d25bb63a2d3b4c63524cd10abe39420dc68c'},
        success: function (response) {
            var data=response;
            $(".show_lnk").html('<img src="'+data.image+'" style="width:30px;height:30px;" ');
            console.log(data.image);
        }
    });
});

Solution

  • I'm not entirely sure where you are stuck, but this will display the response data in some simple tags inside of a dedicated <div>. How you manipulate the css is totally up to you.

    I've pre-loaded google.com into the textarea, so the only thing you have to do is trigger the function by causing a blur event (tab or whatever).

    $(document).ready(function() {
      $("textarea[name*='user_status']").blur(function () {
        var target = $(this).val();
        $.ajax({
          url: "https://api.linkpreview.net",
          dataType: 'jsonp',
          data: {q: target, key: '5a2e292e7d25bb63a2d3b4c63524cd10abe39420dc68c'},
          success: function (response) {
            $("#show_lnk").html('<img src="'+response.image+'"><h3>'+response.title+'</h3><h4>'+response.description+'</h4><a href="'+response.url+'">'+response.url+'</a>');
          }
        });
      });
    });
    body {
        padding: 25px;
    }
    
    #show_lnk img {
      width:30px;
      height:30px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea class="form-control" placeholder="" id="url" name="user_status">google.com</textarea>     
    <div id="show_lnk"></div>