How to Open an Image in a New Tab Using HTML and JavaScript?

Estimated read time 1 min read

You can open an image in a new tab using HTML and JavaScript by creating an anchor <a> element with a href attribute set to the URL of the image, and a target attribute set to _blank. Then, you can use JavaScript to dynamically add the anchor element to the document and trigger a click event on it to open the image in a new tab.

Here’s an example:

<button onclick="openImage()">Open Image</button>

<script>
  function openImage() {
    let imgUrl = "https://www.example.com/image.jpg";
    let a = document.createElement("a");
    a.href = imgUrl;
    a.target = "_blank";
    a.click();
  }
</script>

In this example, clicking the “Open Image” button will dynamically create an anchor element with the href attribute set to the URL of the image and the target attribute set to _blank, and then trigger a click event on it to open the image in a new tab.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply