Home  >  Q&A  >  body text

How to link an image with a URL using Javascript?

I have an image that I want to link to 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 to open some other page which is linked to this image via url.

what should I do?

I tried it, but it didn't work.

Code(I took this from Stack Overflow)

P粉652495194P粉652495194180 days ago315

reply all(1)I'll reply

  • P粉638343995

    P粉6383439952024-04-04 00:26:46

    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)
    }
    
    }

    Image will show here

    I hope this simple code snippet helps you.

    reply
    0
  • Cancelreply