0

I thought this would be easier, but clearly I haven't touched JavaScript/HTML in a long time. I am closer with the following code to getting this to work, yet it seems like webpage still throws an error:

GET https://newapo.apo.nmsu.edu/media/skywatcher/dailyVids/[date]_24hr.webm net::ERR_ABORTED 404 (Not Found)

So the following seems to just not be working at the right 'time' as the alert that pops up is the correct string.

<script>
    document.querySelector('#daily').src = document.querySelector('#daily').src.replace('[date]', finalDay);
    alert(document.querySelector('#daily').src);
</script>

Later in my HTML code I want to use that finalDay as part of a dynamic link:

<div class="col-xs-6 col-sm-6">
          <p> Video (Last 24Hours): </p>
            <video width="800" controls="controls" preload="metadata">
              <source id="daily" src ="{{ MEDIA_URL }}skywatcher/dailyVids/[date]_24hr.webm#t=0.5" type="video/webm">
            </video>
</div>

This is in a Django template though this particular page is doing no server side items. In reality the src should be:

<source src ="{{ MEDIA_URL }}skywatcher/dailyVids/20220512_24hr.webm#t=0.5" type="video/webm">

So not sure, I thought I could use some special tag like {{ }} to have it show up but realized that is variables coming FROM the Django server. Hopefully I don't have to do a whole innerHTML call figuring out somehow what that source src id is etc...

Is there really no way to insert a JavaScript variable easily into HTML?

3
  • 1
    You need a client-side template framework for this. Commented May 13, 2022 at 19:45
  • You do it with JavaScript. Make the source have some kind of easily found string. E.g.., <source src="{{ MEDIA_URL}}skywatcher/dailyVids/[date]_24hr..."/>. Then document.querySelector('source').src = document.querySelector('source').src.replace('[date]', finalDay); Commented May 13, 2022 at 19:48
  • Does this answer your question? Javascript variables in HTML attributes Commented May 13, 2022 at 19:50

2 Answers 2

1

you could simply add an id attribute to your source tag, then use:

if you add this arribute to source tag

<source id = "source">

then

finalDay = someCalculatedDate();

const source = document.querySelector("#source");
source.src = `${MEDIA_URL}skywatcher/dailyVids/${finalDay}_24hr.webm#t=0.5`

media_url and finalday are javascript variable

Sign up to request clarification or add additional context in comments.

5 Comments

Edited the answer, this (and the previous comment) came close to helping but there is some race condition it seems now...like the javascript is not running first before the page loads? wasn't there some simple tag for that...
if you add the script tag at the buttom of body in your html, js load after the time when whole dom elements will created so in this way, there is no problem from this prospective... about dynamic html attribute if you wish for, honestly I don't know if it exists.
Ahh I did added the script tag at the bottom of another codeblock (django defined in my base.html) so it should load after the top part with the actual dummy URL is loaded...it does see it and change it just not in final HTML for some reason still.
another thing maybe could be useful is use script tag with defer flag, if you use script with defer flag you could add it anywhere(in head) and in this way you could be sure the JavaScript loaded after painting dom... and maybe use a webapck as bundler to make sure about management of those.
Didn't know that flag existed until now. I did try it but something else must be going on. Java script at bottom, in a defer tag and still the src isn't getting updated so still gets a 404 not found. This might have to do with the urls.py and other issues specific to django routing though.
0

UPDATE

Changed .toLocaleDateString('en-US') to .toLocaleDateString('en-GB'), I forgot US doesn't pad with zeros and the UK does. The difference is:

Lang-Country Format Example
en-US D/M/YYYY 1/1/1970
en-GB DD/MM/YYYY 01/01/1970

Assuming `finalDay()` is a function that returns a string of today's date in this form: `yyyymmdd`, it should use the `Date()` constructor to get today's date and then the following methods:
  1. .toLocaleDateString('en-GB'), returns a string: "05/13/2022"
  2. .split('/') to remove all "/", returns an array ["05","13","2022"]
  3. .reverse() to switch "05" and "2022" around, returns an array ["2022","13","05"]
  4. .join('') to combine the array into a single string, returns "20221305"
const finalDay = function() {
  const today = new Date(); 
  return today.toLocaleDateString('en-GB').split('/').reverse().join('');
}

Next, interpolate that string from finalDay() into a template literal (a string with superior syntax):

const url = `${MEDIA_URL}skywatcher/dailyVids/${finalDay()}_24hr.webm#t=0.5`;

Unfortunately MEDIA_URL is unknown (either you don't know it yet or you forgot to include it?), so we will continue with a working example. You can replace the following url with the one above if or when you have MEDIA_URL:

const vidSrc = document.querySelector('source');

// This is a working example
vidSrc.src = `https://glpjt.s3.amazonaws.com/so/av/vid5.mp4`;

let MEDIA_URL;

const finalDay = function() {
  const today = new Date(); 
  return today.toLocaleDateString('en-GB').split('/').reverse().join('');
}

const url = `${MEDIA_URL}skywatcher/dailyVids/${finalDay}_24hr.webm#t=0.5`;

const vidSrc = document.querySelector('source');

// This is a working example
vidSrc.src = `https://glpjt.s3.amazonaws.com/so/av/vid5.mp4`;

// This is the real src for your OP
/*
vidSrc.src = url;
*/
console.log(`This is what the real segment would look like without MEDIA_URL`)
console.log(`skywatcher/dailyVids/${finalDay()}_24hr.webm#t=0.5`);
<video width="800" controls="controls" preload="metadata">
  <source type="video/webm">
</video>

4 Comments

MEDIA_URL Is from django so it knows where the media repository is. Though I thought maybe the django was holding up the processing so I took out media URL and tried this version where it changes it as you stated here. It works, if I post what the .src ends up equaling but it doesn't actually 'write it back' to the html, so if I look at the source of the HTML it just shows : <source id="daily" type="video/webm"> So it never actually gets written back
Updated I forgot it's ${finalDay()}, and changed vidSrc to point to <source>. Notice that the video is MP4 but the type="video/webm" yet it still plays? That type attribute is a suggestion -- modern browsers are smart enough to ignore it if it's wrong.
@Codejoy Sorry, read the latest update concerning US and UK formatting.
@Codejoy One more thing, if you intend to use only one video, you don't have to use <source> -- you can add src attribute to <video> instead. <source> is used for multiple versions of the same video, like for example you have video.mp4 and video.webm and/or a video at 720p resolution, and the same video at 1080p resolution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.