0

I have some code which generates a dynamic date string, I want to put in into a web link so I can call the link to generate a new image each day.

I have written this code:

<script>
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();

document.getElementById("link").href = "http://earth.nullschool.net/#" + year + "/" + month + "/" + day + "/1200Z/wind/isobaric/500hPa/";
</script>

<a href="http://earth.nullschool.net/#2012/01/24/1200Z/wind/isobaric/500hPa/" id="link">500 mb Earth Wind Map</a>

However when I click this link it goes to the old date (2012), not the current date that the javascript creates. How do I create the link with today's date inside it?

Pad
  • 841
  • 2
  • 17
  • 45
  • You should place the script *below* the element that it wants to modify. If the order is as you have depicted it, then you should get an error message in the console. – trincot Jun 02 '21 at 16:28
  • You are getting an error in your console about `href` not being a property of null... – Heretic Monkey Jun 02 '21 at 16:40

2 Answers2

1

You need to place the anchor tag before the script.

<a href="http://earth.nullschool.net/#2012/01/24/1200Z/wind/isobaric/500hPa/" id="link">500 mb Earth Wind Map</a>

<script>
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();

document.getElementById("link").href = "http://earth.nullschool.net/#" + year + "/" + month + "/" + day + "/1200Z/wind/isobaric/500hPa/";
</script>
Eric
  • 311
  • 1
  • 6
0

I am not sure if this works but it should so for your last line you can do this instead

<a href="http://earth.nullschool.net/#{}/{}/{}/1200Z/wind/isobaric/500hPa/".format(year,month,day) id="link">500 mb Earth 

Since you are using a format method u are substituting your variable into the brackets.

AHBLUBLU
  • 33
  • 6