Explain Codes LogoExplain Codes Logo

How to open link in a new tab in HTML?

html
responsive-design
performance
javascript
Alex KataevbyAlex Kataev·Sep 3, 2024
TLDR

Open a link in a new tab in HTML by using the target attribute with _blank value in your <a> tag, as shown below:

<a href="URL" target="_blank">Link Text</a>

Replace URL with your desired link and Link Text with the visible, clickable text.

For secure new tab opening, add rel="noopener noreferrer" to your <a> tags:

<a href="URL" target="_blank" rel="noopener noreferrer">Link Text</a>

Our friendly HTML tag is now armored against potential tab-nabbing!

Default targets with <base> tag

Use the <base> tag in the <head> section to set a default target for all links:

<head> <base target="_blank" rel="noopener noreferrer"> </head>

Never forget: the <base> tag has your base-line back!

Be the maestro of your link's behavior with these target settings:

  • target="_self": Link opens in the same frame or window.
  • target="_parent": Navigates out of an iframe or nested browsing context.
  • target="_top": Escapes any and all frames. The linked document rules supreme.
  • target="framename": Specifies where a link should open within a hierarchical structure.

Employing JavaScript when new tabs are blocked

If new tabs are blocked, beckon the powers of JavaScript with window.open:

function openLinkInNewTab(url) { window.open(url, '_blank').focus(); } // "Please grant me passage, dear browser!"

Trigger this function with an onclick event.

Utilizing dynamic scripting for secure linkage

Add security enhancements to external links dynamically with some jQuery ninja magic:

$("a[href^='http']").not("a[href*='" + window.location.host + "']") .attr("target", "_blank") .attr("rel", "noopener noreferrer");

Allory, the jQuery ninja, says: "All external links, be gone!" 🐱‍👤