How to open hyperlinks in a new window in HTML

Overview

The HTML <a> tag defines a hyperlink. By default, it opens the target URL in the same tab. This default behavior can be changed in one of two ways.

Using pure HTML: Letting the browser decide

The simplest way is using the target attribute. The '_blank' tells the browser to use a new window or tab. However, most browsers default to using a new tab instead of a new window.

target="_blank"

Using inline JavaScript: Forcing a new window

In JavaScript, the window object represents the browser window. The open() method of the window object can be used to create a new window.

window.open(url, target, windowFeatures);

Parameters

The parameters of window.open method are as follows:

  1. url: The URL to load.
  2. target: The context name to use for the new window.
  3. windowFeatures: A comma-separated string of additional options.

On line 6, window.open is used with the onclick attribute within the <a> tag. Parameters passed to window.open are as follows:

  1. this.href: It refers to href , the URL already specified in <a> tag.
  2. 'new': It is an arbitrary value for the target.
  3. 'popup': It is one of the windowFeatures that ensures a new window is opened for a hyperlink.

Lastly, return false; makes sure the original window is not redirected.

Copyright ©2024 Educative, Inc. All rights reserved