views:

78

answers:

4

Hi,

I wish to have a link which opens popup when clicked however I wish it to open a page in a new window if the user doesn't have JS enabled.

The following doesn't seem to work,

<a id="tac-link" target="_blank" href="tac.html">terms and conditions</a>

function popUp(URL) {
day = new Date();
id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=600,left = 445,top = 150');");
    }

$('tac-link').click(function() {
    popUp('tac.html');
    return false;
});
A: 

In order to make this functionality more browser-compatible, you need to pass the event object to the click handler, then call e.preventDefault();.

example:

$( '#button' ).click( function( e ) {
    //... your code...

    e.preventDefault();
    return false;
} );
Jacob Relkin
Ah ha what a fool I am! Thanks!
pakooz
A: 

You simply missed the # indicating it's an id and not a node name.

$('#tac-link')


PS - I wouldn't recommend using eval, why not just store all the page variables in an object?

var pages = {};

function popUp( url ) {
    var id = +new Date;
    pages[id] = window.open( url );
}
meder
A: 

Also note that event.preventDefault is not present in all browsers and will cause an error in things like IE7 (if memory serves.) To avoid that, use a general if-statement:

if (e.preventDefault) {  
    e.preventDefault();  
}  
e.returnValue = false;

This will prevent the error from being thrown. I believe jQuery uses this approach as well.

Reid
jQuery wraps the browser event with it's own object, which exposes a `preventDefault` method so devs don't have to worry about this detail. Not that this matters for this question, as `return false` is a special trigger for jQuery to call `preventDefault()` under the hood for you.
Crescent Fresh
That must have come out recently, then; last time I tried to do a `preventDefault` it threw an error in one of the IEs (6 or 7.) Ever since then, I've been doing the whole returnValue deal.
Reid
+4  A: 

I think you just have the id selector wrong. Try changing $('tac-link') to $('#tac-link').

Another approach:

$('a[target="_blank"]').click(function(e) {
    window.open( this.href );
    e.preventDefault();
});
David