0

I want to add this code in a custom HTML widget of wordpress website but the problem is that I am unable to create and use date-wise image link. By seeing the code below, please tell me what is wrong here and how to correct it:

<html>
<head>
<script type="text/javascript">


var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();
if(dd<10){
    dd='0'+dd;
} 
if(mm<10){
    mm='0'+mm;
} 
var today = yyyy+'/'+mm+'/'+'dd';
var link = "http://e.piyarawatan.com/paper/" + today + "p-1.jpg";

</script>
</head>
<body>
<img src='<script type=javascript>link</script>'>aaa</img>
</body>
</html>

The output should be an image but it is not. Here the the output:

aaa

After compiling, the image goes to this link : http://news.piyarawatan.com/%3Cscript%20type=javascript%3Elink%3C/script%3E which is an invalid link

2
  • You tell us what's the problem. Commented Mar 13, 2018 at 19:16
  • I edited. check the last lines Commented Mar 13, 2018 at 19:22

3 Answers 3

1

You cannot reference a JS variable like that in HTML. You need to give the image tag an id, and dynamically set the src attribute of this element. Like so:

<html>
<head>
<script type="text/javascript">

document.addEventListener("DOMContentLoaded", function(event) {

  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!

  var yyyy = today.getFullYear();
  if(dd<10){
      dd='0'+dd;
  } 
  if(mm<10){
      mm='0'+mm;
  } 
  var today = yyyy+'/'+mm+'/'+dd;
  var link = "http://e.piyarawatan.com/paper/" + today + "/p-1.jpg";
  console.log (link)

  document.getElementById("image1").src = link;
});

</script>
</head>
<body>
<image id="image1"/>
</body>
</html>

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

1 Comment

the edit I made fixes the link to match what looks right for this site (e.piyarawatan.com/paper/2018/03/01/p8.htm), but there isnt an image for today, so it isnt going to work
1

This line:

var today = yyyy+'/'+mm+'/'+'dd';

should be:

var path = yyyy+'/'+ mm +'/'+ dd + '/';  

Don't re-declare today, use a new variable instead for clarity. Then the next line should read:

var link = "http://e.piyarawatan.com/paper/" + path + "p-1.jpg";

Finally, you aren't interpolating here correctly either:

<img src='<script type=javascript>link</script>'>aaa</img>

One way to do this is:

document.write('<img src="' + link + '" />');

inside your script tag.

Comments

0

This might answer your question: html image src call javaScript variable

Comments

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.