Home > Software design >  Image with dynamic url won't link anywhere
Image with dynamic url won't link anywhere

Time:02-15

Absolute newb to coding so my apologies if my question is phrased poorly! I'm trying to get an image that has a dynamic url to send users to another url when it's clicked on. The image has a dynamic url so that I can remotely update the gif if needed without caching issues. My problem is that I can't seem to get the image to link to anywhere when it's clicked on. I've tried putting it in a div container and using the usual tags but it doesn't seem to work. How can I get the image to link the person to a new url location when they click on it?

Here's the code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() 1; //January is 0!
var yyyy = today.getFullYear();
today = yyyy   ''   mm   ''   dd;
var myImage = new Image(400, 190);
myImage.src = 'https://www.conatycatering.com/image/uploads/signatures/topsignature'   today   ".gif";
document.body.appendChild(myImage);

$("a#url").attr("href", url)
});
</script>

Many thanks for any help!

CodePudding user response:

So one part you were missing is declaring the url. Once you've done that however, you want the image to be inside the anchor, not the general body.

So you don't want to use document.body.appendChild which just adds the image to the HTML body, you instead want the image inside the anchor, which you can see working below, by setting the html() of the anchor.

$(document).ready(function(){
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() 1; //January is 0!
  var yyyy = today.getFullYear();
  today = yyyy   ''   mm   ''   dd;
  var myImage = new Image(400, 190);
  myImage.src = 'https://www.conatycatering.com/image/uploads/signatures/topsignature'   today   ".gif";
  
  var url = 'http://example.com' // REPLACE THIS WITH YOUR URL
  $("a#url").attr("href", url)
  $('a#url').html(myImage)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<a id="url"></a>

I've removed a lot of extra stuff and used a placeholder image for brevity.

  • Related