Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to open all external links in a new window

New to jQuery here. I've found several web pages that come close to what I'm trying to do, but not quite. Actually, I think the following is supposed to actually work, but it's saying:

[@href^="http://"]

is not recognized (syntax error). Any help?

$(document).ready(function() {
    $('a[@href^="http://"]').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).attr('target', '_blank');  
});

Thanks.

like image 867
Jeff Lamb Avatar asked Dec 09 '09 03:12

Jeff Lamb


People also ask

How do I make links open in a new window by default?

How to Open Hyperlinks in a New Browser Tab or Window. The short answer is: just add a target="_blank" attribute to your links (anchor tags). Now when your visitors click that link, it will open in a new window or tab (depending on which web browser they are using and how they configured that browser).

Should external links open in a new window?

External links, for instance, should always open in a new browser tab. Your goal in designing a website is to get more visitors to convert. Letting an external link replace your website in the open tab will only decrease the chances of that happening.

How can you open a link in a new browser window in JavaScript?

In JavaScript, window.open() method is used to open a new browser window or a new tab depending on the browser setting and the parameter values.


1 Answers

No need for the @ symbol. Other than that, you're golden.

$("a[href^='http://']")...
like image 79
btelles Avatar answered Sep 22 '22 01:09

btelles