Nik
Nik

Reputation: 472

Javascript link with the ability to open in new tab/window

I'm trying to get a link that will both open in the current page, or when command/ctrl clicked (etc.) will open in a new tab/window based on the users settings. Right now I'm using something like this:

<a href='http://example.com' onclick="setTimeout(function() {window.location='/some_local_page'}, 10); return false;">Foo!</a>

This allows me to click on the link and have it open the local page, but I have to explicitly right click and choose open in new tab/window. I'm pretty sure this is a solved problem, but I can't find the right combination of google/stackoverflow keywords. :)

This might help for clarification:

<a href='http://example.com' onclick="some_javascript_function(); return false;">Foo!</a>

In this case a click should call some_javascript_function() and a command/ctrl click should open "http://example.com" in a new tab/window and do nothing to the current page.

Upvotes: 1

Views: 5322

Answers (2)

gen_Eric
gen_Eric

Reputation: 227240

Is this what you want?

<a href="http://example.com" onclick="window.open('/some_local_page')">Foo!</a>

Or this?

<a href="/some_local_page" target="_blank">Foo!</a>

EDIT: The onclick will fire when the center or left button is clicked (but not the right button).

So, in the onclick, you need to detect if ctrl was pressed, or if it was the middle button.

I also suggest not putting JavaScript inline. Try this:

<a href="http://example.com" class="link" data-link="/some_local_page">Foo!</a>​

$('a.link').click(function(e){
    if(e.button === 0 && !e.ctrlKey){ // Click without ctrl
        e.preventDefault();
        // open local page
        window.location = $(this).data('link');
    }
    // Middle click and ctrl click will do nothing,
    // thus allowing the brower to open in a new window
});​

DEMO: http://jsfiddle.net/E8hEt/

Upvotes: 7

ShankarSangoli
ShankarSangoli

Reputation: 69905

Why don't you render the same url in its href attribute if you want go to the same url?. And to open it in a new window set the target to _blank.

<a href='/some_local_page' target='_blank'>Foo!</a>

Upvotes: 1

Related Questions