Search code examples
javascriptjqueryiframe

Change the link inside of an embed on each matching anchor link


I'm working with a very limited system that doesn't allow for direct HTML editing so anything I want to add is only capable through Javascript / JQuery (which I'm still very new at).

What I'm trying to do is as follows:

  • Identify links with a matching pattern
  • Have its href value stored
  • Inject HTML code to display an iframe
  • Replace the video href the iframe references to the href stored earlier
  • Loop for every matching href on the page

So far, I've been able to get the iframe to display with the correct video, however, if I add multiple matching links - but to different videos/hrefs - the result is the exact same embedded video repeatedly.

Here's my code so far:

  $('a[href*=\"https://app.application.io/recordings/\"]').each(function(index,item){
  var applicationEmbed = $(this).attr("href");
  var applicationiFrame = '<div class=\"video-embed\" style=\"position: relative; padding-bottom: 50.5%; height: 0;\"><iframe src=\"' + applicationEmbed + '/embed\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%;\"></iframe></div>'
    $("a[href*=\"https://app.application.io/recordings/\"]").replaceWith(applicationiFrame);
    });

Any tips?


Solution

  • It's because your last line is telling the script to replace every instance of the link pattern $("a[href*=\"https://app.application.io/recordings/\"]") with the single value replaceWith(applicationiFrame), which is making them all the same. Here's an alternate approach an note how I used template literals to help with readability.

    $('a[href*=\"https://app.application.io/recordings/\"]').each(function(index, item) {
      let applicationEmbed = $(item).attr("href");
      let applicationiFrame = `
      <div class="video-embed" style="position: relative; padding-bottom: 50.5%; height: 0;">
      <iframe src="${applicationEmbed}/embed" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe>
      </div>`
      $(item).before(applicationiFrame).remove()
    });
    .video-embed {
      border: 1px solid #666;
      background: #dedede;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="https://app.application.io/recordings/1">Test link</a><br />
    <a href="https://app.application.io/recordings/2">Test link</a><br />
    <a href="https://app.application.io/recordings/3">Test link</a><br />
    <a href="https://app.application.io/recordings/4">Test link</a><br />