Javascript: onClick Open Link in New Tab (HTML Button)

At times we want to open a new tab by clicking a link or a button in our webpage. This is usually done when we want to open an external website without taking the user away from our own webpage. This being a very often used functionality by webmasters –ways to accomplish this have been developed using HTML as well as JavaScript.

onClick Open a New Tab Using JavaScript

If you have an HTML button, you can use the following JavaScript code to open a desired URL in a new tab when user clicks the button.

<input type="button" value="New Tab" onclick="window.open('http://www.example.com')">

Remember, this method will open either a new tab or a new window depending upon the default settings of the user’s browser. However, nowadays, all the browsers provide multi-tab view and the default is to open a new tab.

JavaScript is beautiful!
onClick Open a New Tab Using HTML

If you want to open a link in a new tab –the easiest way is to use target attribute of ANCHOR element in HTML. Here is how you need to do it.

<a href="http://www.example.com" target="_blank">Example.com in a new tab</a>

SEE ALSO: Open Recently Closed Tabs in Chrome

Tip 1: Here the target attribute is set to _blank. This value opens a new tab/window. If you are using a frame in your webpage (iframe or frameset) you can give name of the frame as target value to open the URL in that particular frame. For example:

<a href="http://www.example.com" target="mainframe">Open inside a frame</a>

Tip 2: Target attribute can also to use to open a link from inside a frame into the entire tab (this is called frame breaking). To do so, just give _top as the value of target attribute. And voila! Link will break the frame and open in the whole tab.

TIP 3: If you want, you can also use CSS to stylize your link to look like a button.

I hope this tip was useful for you. Please let me know if you have any questions in this regard. Thank you for using TechWelkin!

5 thoughts on “Javascript: onClick Open Link in New Tab (HTML Button)”

  1. Hi,

    Very nice information. These all above method work perfect for normal link.

    I’m looking for applying this technique on Alexa Widget. I tried it, but it is not working. Can you please have a look?

    Thanks & Regards,
    Gulshan

    1. Hi Gulshan, Alexa widget is rendered by the JavaScript code given by Alexa. So, you can’t (and should not) change it. I can do something to open Alexa link in a new tab but that would not be a legal thing to do.

  2. Can you think of a way on a site which uses javascript to allow the user to choose to open in a new tab (rightclick – open in new tab); it seems to me that javascript takes that choice away from the user.
    Thanks

    1. I guess the easiest way would be to use buttons instead of regular links. And then capture right click event to open a new tab.

Leave a Comment

Your email address will not be published. Required fields are marked *