Home > database >  I have an image and I want to link it with a url. How can I do that? I am using Javascript
I have an image and I want to link it with a url. How can I do that? I am using Javascript

Time:01-21

I have an image and I want to link it with a url. I have used javascript. Code after running the code I want to display this image and when I click on it I want some other page to open that has been linked to this img with a url.

how can I do that?

I tried this but it doesn't work.

Code(I took this from Stack Overflow)

CodePudding user response:

It's easy and you don't need JS to do that.

Follow here:

<img  src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/cats.jpg"  alt="Five cats looking around a field."/>

If we wanted to make that image a clickable link, then we can place it inside a set of anchor tags.

<a href="https://en.wikipedia.org/wiki/Cat"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/cats.jpg" alt="Five cats looking around a field."/></a>

We can also add the target="_blank" attribute to have that link open up in a new tab.

<a target="_blank" href="https://en.wikipedia.org/wiki/Cat"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/cats.jpg" alt="Five cats looking around a field." /></a>

When you hover your mouse over the image, you will see the cursor pointer indicating that it is a link directing you to an article about cats.

CodePudding user response:

function handleClick(){
 const image = new Image ()

image.src = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
image.style.width="200px"
image.style.height="200px"
image.alt="Google logo"
image.addEventListener("click", function() {
  window.location.href="https://www.google.com"
})

const element = document.getElementById('image-container')
if(element){
   element.appendChild(image)
}

}
<h3> Image will show here </h3>

<div id="image-container"></div>
<button onclick="handleClick()">Show  me </button>

I hope this simple snippet will help you.

  • Related