Languages
[Edit]
EN

JavaScript - open link in new tab

5 points
Created by:
Kate_C
2860

In this short article we would like to show how in JavaScript open some link in new tab.

Quick solution:

// ONLINE-RUNNER:browser;

window.open('https://dirask.com', '_blank');

Notes:

  • many browsers blocks popupping windows this way -¬†sometimes it is better to¬†consider simple link in html code with target="_blank" attribute,
  • to avoid browser blocking effect it is good to run above action inside mouse click event¬†function - check last example.

Read next sections for more details.

Link with click symulation example

In this approach it is necessary to create new link element and simulate clicking on it.

// ONLINE-RUNNER:browser;

var a = document.createElement('a');

a.setAttribute('href', 'https://dirask.com');
a.setAttribute('target', '_blank');

a.click();

Avoiding blocking by web browser example

In this section, open in new window action is run during onclick event to prevent blocking operation.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <span onclick="window.open('https://dirask.com', '_blank')">
    Click me and open new tab
  </span>
</body>
</html>

 

Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.