Explain Codes LogoExplain Codes Logo

Html button opening link in new tab

html
responsive-design
best-practices
accessibility
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

To quickly open a link in a new tab from an HTML button, use the window.open() function in the button's onclick attribute:

<button onclick="window.open('https://www.example.com', '_blank')">Open New Tab</button>

The key points involve using onclick="window.open('URL', '_blank')" where 'URL' is your desired destination, and '_blank' specifies the new tab target.

Solutions for various scenarios

In the realm of HTML, multiple solutions coexist for different requirements. Let's chart some valuable resolutions:

Implementing anchor tags for cross-browser compatibility

To ensure consistent behavior across all browsers and platforms, wrap the button element in an anchor (<a>) tag.

<a href="https://www.example.com" target="_blank"> <button type="button">Open New Tab</button> </a>

This approach takes advantage of <a> tags' built-in ability to open links in new tabs while retaining button features.

A form element with the target="_blank" attribute offers a more semantic method to launch URLs in new tabs:

<form action="https://www.example.com" target="_blank" method="get"> <button type="submit">Open New Tab</button> </form>

This technique shines when dealing with data submission, aligning with forms' inherent behavior.

Adding return false to prevent default behavior

After invoking window.open() through onclick, tack on return false to prevent any default button action:

<button onclick="window.open('https://www.example.com', '_blank'); return false;">Open New Tab</button>

Enhancing user experience consciousness

Being conscious about user experience when implementing new-tab links allows avoiding disorienting experiences for users. The usability principles urge to use screen-reader-friendly attributes for enhanced accessibility whenever possible.

When _blank target might not be the best idea

While _blank is incredibly useful, its overuse can fragment a user's experience. Avoid unnecessary usage to circumvent potential performance issues stemming from multiple tabs.

Non-JavaScript alternatives

Non-JavaScript scenarios may need the HTML5 download attribute for resources that should be opened in a different tab.

<a href="https://www.example.com/document.pdf" download> <!-- Download the future... Literally! 😄 --> Download Document </a>

Accessibility considerations

Incorporate the rel="noopener noreferrer" on <a> elements with _blank target value for improved accessibility and security:

<a href="https://www.example.com" target="_blank" rel="noopener noreferrer"> <!-- This link takes no prisoners! ⛓️ 😉 --> Visit Example </a>