Loading a link in field in a Javascript application

Leaving this a bit more open ended in case there are applications elsewhere, but here’s my situation.

I’d like to load the link for an MP4 file using Video.js HTML5 video player. I have the link stored in a field. The player loads just fine in a rich text view when I hard code the link into it, but I cannot use a field variable to dynamically load in the video for different records. My ideal scenario is to create a detail view for each record with a video link and be able to view it alongside other fields (metadata) for that video. Any ideas?

Hi @GSergeant,

I would say to create a Text Formula with your HTML that contains {Video URL} as a variable, but Knack strips away HTML video tags when trying to store them, so the next best thing is Javascript in my opinion.

In the Builder, create a detail view that contains the link, then use Javascript to replace the link with HTML when the view is rendered.

In the code below, you’ll want to replace the view and field numbers to your own.

// Assumptions: 
// You have a Detail view that contains a field that is a video link.
// You want the video link to display inside an HTML5 player. 
$(document).on('knack-view-render.view_177', function (event, view, data) {
  // The view is rendered...

  // Create a reference to the field and value
  const $field = $(`#${view.key} .field_253 .kn-detail-body`)
  const fieldValue = $field.text()
  
  // Replace the HTML with video tags and place the link inside. 
  $field.html(`
    <video width="320" height="240" controls> 
      <source src="${fieldValue}" type="video/mp4"> 
    </video>
  `)
})

Before:

After:

Then in the Builder, set the Label Format to None for that view so it doesn’t say “Video Link”.

Ian

1 Like

That really does the trick. Thank you! - and I assume that this can be used for anything that needs an HTML wrapping that Knack will otherwise strip out in a text formula?

1 Like

Yep!