Question

I've got a page with a fair few links, the links currently are target="blank" so if someone accidentally clicks on one they won't ruin what their doing on my page. However, I don't like doing _target="blank" (I always think it's sort of patronising for the user to tell them how to open a link..).

So I thought I'd give the user the option to turn 'open in new window / tab' off. Currently I'm doing this in PHP:

<?php if($newWindow){ echo '_blank'; } ?>

But I would much rather do this in JavaScript if possible (seems silly to reload the whole page just to change a few strings). How would I do that? I've found lots on changing input fields and the like, but not link attributes..

Oh, and not in jQuery if at all possible. If it is possible using CSS that would be cool, but I'm assuming it's not come quite that far yet..

Was it helpful?

Solution

Somewhere on your page (should be true/false):

var newWindow = <?=$newWindow;?>

Then do (jQuery, just concept though):

$('a').bind('click', function(event){
    if(newWindow){
        event.preventDefault();
        window.open($(this).attr('href'));
    }
});

There are a few ways of doing it, but this one came to mind first. This obviously requires you to also handle relative links - so keep that in mind.

Edit: Due to @durbnpoisn giving me greif, here's the code ready for you to drop into your site:

Link:

<a id="toggle-new-tab">Turn on/off new window</a>

JS:

var newWindow = false;
document.getElementById('toggle-new-tab').onclick = function(){
    newWindow = !newWindow;
}

var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++){
    if(links[i].href !== '')
        links[i].onclick = newWindowHandler;
}

function newWindowHandler(event){
    if(newWindow){
        event.preventDefault();
        window.open(event.target.href);
    }
}

Demo: http://jsfiddle.net/qY7sh/1/

OTHER TIPS

Try:

document.getElementById("[anchor id]").target = "_blank";

This should work, assuming your "a href" has an ID.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top