Css link new windows

Open Link in a New Window

HTML attribute (valid in HTML5 now):

Inline JavaScript way:

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Comments

I think some code might have gotten stripped there. Feel free to email me at [email protected] to fix.

Using the second approach opens the href in my current (parent) window too. i.e. my current window and new window both points to href value. I don’t want my parent window to be changed

My purpose was to open a link in new window,

i tried this, but my parent window(which has link) becomes blank when i click on the link.

It doesn’t work because it should be:

onclick=”window.open(this.href,’_blank’); return false;”

it doesnt though

Target-blank is not strict xhtml (it might be considered as behaviour that should not be placed in the mark-up) and it can make people angry when used on every link, especially the internal ones. But sometimes it can be useful, if there’s an external link among many internal links.
Personally I prefer to use CSS-Content to set a “(ext)” behind those links via auto-detection (attr).

I’d say it’s a bad practice. Because if I want to open link in new window, jsut press shift+mouse key. Or middle button (to open in new tab).

I’d say it’s the best practice to use target=”_blank”, because it simply works.
There are people who don’t know that you can press the middle mouse button or other shortcuts. Nobody will see it at the end. Why should I not break the rule on this point?

How with auto open in new windows?

sorry, i’m newbie in CSS 😀

Thanks! PDFs don’t seem to honor _blank.

hey Jason, for PDF’s use, target=”_new”

This snippet was very useful, thank you!

I think this article is misleading, it clearly states that target=”_blank” is invalid which isn’t true. It’s perfectly valid in both HTML5 and XHTML 1.0 Transitional. It’s only invalid in the strict DTD, but who uses that?
There’s no real reason not to use the target attribute, every browser supports it and will support it for the foreseeable future. And besides, why use JavaScript for something that the browser can do natively?

any benefit/downside to using html instead of JS or vice versa?

This sort of thing should br strongly discouraged. Only ever should a website had a teeny tiny sprinkle of target=»_blank» atop its icing. It is entirely the user’s choice as to whether they want another tab/window opened or not. It doesn’t matter if some users don’t know how to click with the middle-button; who are we to force new tabs upon those who do know how to open links in new tabs for the sake of the few ignorant users out there.

I’ve come across quite a few websites where links open in new tabs when they just shouldn’t and it’s frustrating, because I wanted the link to open in the current tab.

Leave target=»blank» alone unless you absolutely need it.

Perfect! exactly what i’m looking for. thanks 🙂

There actually IS a need for links to open in a new windows… sometimes. I am designing and coding a site which collects data from users which requires them to upload files (images and pdf documents). The overall process involves employees filling out a form and then uploading receipt scans/images for reimbursement. This needs to be viewed by an admin intranet site within the office. I have a nice page displaying the claim in a cute form, easily printable if required, and links to the relevant file uploads.

I don’t want those links to take over the parent window. They are additional info to the data displayed in the parent window, so they are required to open in a new window or tab (based on browser preference settings) while leaving the parent windows alone. Frequently both windows will be examined and compared together. Hard to do if only one is open at a time!

Читайте также:  Windows 10 как поменять заставку рабочего стола

And no, our accounts team are not IT knowledgeable enough to recognise how/when to choose to open a link in a new windows. They expect it done for them. And quite rightly so too.

Having said that, this is a rare case and I would not normally utilise this in any other way or for any other reason. It bothers me that using target=”_blank” is not acceptable in strict html5 mode. I always code my html/css/php to perfect strict acceptance levels. Well…. I did until now. This is the exception. :/

How to Open CSS Menu Links in a New Window.

CoffeeCup Software

ID# 698

You must be signed in to rate articles.

Follow these instructions to set your CSS menu links to open in a new window:

1. If you haven’t done so already, insert your menu code into your page. (For more information about this process, read How to Use the CSS Menu Designer.)

2. Look for the HTML menu code on your page. It will look like this:

In this example, we have used generic values (class=»menu-menu», page1.html, Menu Item 1, etc.). The values in your menu may differ.

3. For every link you want to open in a new window, place the following attribute-value pair inside the opening link tag ( ): target=»_blank». This means your code will look like this:

That’s all there is to it! If you want, you can go ahead and preview your menu using one of the preview options in the program.

The Short Story

We started in a real coffee house in 1996 with the HTML Editor. Our philosophy has always been to create web design software and services so you can make better Websites. We are dedicated to helping you with extraordinary support so we can succeed together.

Make a link open a new window (not tab) [duplicate]

Is there a way to make a link open a new browser window (not tab) without using javascript?

5 Answers 5

With pure HTML you can’t influence this — every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past.

HTML option

You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly «new tab» instead of «new window». You have no influence on that, and you can’t «force» modern browsers to open a new window.

In order to do this, use the anchor element’s attribute target [1] . The value you are looking for is _blank [2] .

JavaScript option

Forcing a new window is possible via javascript — see Ievgen’s excellent answer below for a javascript solution.

(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!

[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)

[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like _parent , _self or _top .

Тег link

Тег link подключает CSS файлы на HTML страницу. Кроме того, link подключает некоторые другие файлы, например, фавикон. (Фавикон — это ярлычок сайта, который виден во вкладке браузера. Его также можно увидеть в некоторых поисковиках при поиске напротив сайтов, например в Яндексе).

У данного тега очень много атрибутов и они могут принимать разнообразные значения, однако в реальной жизни они все практически не используются. Самое популярное — это подключение CSS и добавление фавикона.

Как подключить CSS в HTML5: . В более ранних версиях нужно было добавлять атрибут type в значении text/css. В HTML5 так тоже можно делать, но это не обязательно.

Как подключить фавикон: .

Тег link не требует закрывающего тега.

Атрибуты

Атрибут Описание
href Путь к подключаемому файлу.
media Тип устройства, для которого следует подключить файл.
Что имеется ввиду — вы можете подключить CSS файл только для больших экранов (значение screen) или только для маленьких экранов: для мобильников или планшетов (значение handheld).
Возможные значения: all, braille, handheld, print, screen, speech, projection, tty, tv. Подробнее смотрите ниже.
rel Тип подключаемого файла. Возможные значения: stylesheet | alternate. Значение stylesheet указывает на то, что подключается CSS файл, значение alternate используется, к примеру, для указания ссылки на файл в формате XML для описания ленты новостей, анонсов статей.
charset Кодировка подключаемого файла. В настоящее время стандартом является utf-8.
type Тип данных подключаемого файла. Для CSS следует использовать text/css, для фавикона: image/x-icon.
Читайте также:  Клавиатура windows издает звуки

Значения атрибута media

В HTML5 в качестве значений могут быть указаны медиа-запросы.

Значение Описание
all Все устройства.
screen Экран монитора.
handheld Телефоны, смартфоны, устройства с маленьким экраном.
braille Устройства, основанные на системе Брайля, предназначены для слепых людей.
speech Речевые синтезаторы, а также программы для воспроизведения текста вслух. Сюда же входят речевые браузеры.
print Принтеры.
projection Проекторы.
tty Телетайпы, терминалы, портативные устройства с ограниченными возможностями экрана. Для них не должны использоваться пиксели в качестве единиц измерения.
tty Телевизоры, которые умеют открывать web страницы (бывает и такое).

Значение по умолчанию: all.

Пример

Давайте посмотрим, как выглядит структура простейшей html страницы, к которой добавим подключение CSS файлов и фавикона:

Open External Links In New Window

You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.

Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.

Also note that there are a wide variety of different ways to only target external links.

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Comments

A slightly different version if you only want to target specific URLs (I use the rel tag “external”):

$(‘A[rel=»external»]’)
.click( function() <
window.open( $(this).attr(‘href’) );
return false;
>);

Nice snippet Paul, that’s much better, and beautifully unobtrusive and validates in XHTML 1 strict. It’s about time the world stops using obtrusive javascript.

Thank you, Paul! This came in handy.

Very useful technique. Thanks you so much

Here is something that I believe will add a great value. I just tried to ignore any links that belongs to the site and identify the external links straightforward.

Is there a way to resize the window that pops up as well?

This is awesome. Just what I needed for a client’s website. And thanks Paul, that works wonderful.

Here is a snippet we’re using that works similar to Paul’s and adds support for target “_blank”, “parent”, “top” and “popup”

If code is garbled, grab it here: http://www.id3.co.th/js/lib.js (look for “links and popups”)

You then activate it in your pages by adding externallinks(); in your $(document).ready(function()<

If code is garbled, check the source of http://www.id3.co.th/ (look for “.ready(function”)

Hope this helps!

window.onload = externallinks; for nojquery situation

If you have a good reason for opening certain links in a new window and want to use plain HTML you could just switch to the HTML5 doctype.

It’s the little things in life! Small code, huge solution!

target=”_blank” and just forget about xhtml strict, that is dead by the way.
Everyone is talking about HTML5 now.. why do you waste your time with thes insignificant problems?

I agree with you, why bothering with scripts when we already have target”_blank”, moreover it also works for people with js is disabled! Maybe this isnt a concern anymore?

Because, even in 2010, people still don’t understand the role of validation. It’s a tool, not an achievement. Remember the compliance badge craze!?

if you’re using jquery, you should use delagate. that way, you create 1 event binding on the body element, instead of hundreds, one on each link.

Читайте также:  Меню перед загрузкой windows

code would look something like
$(‘body’).delegate(“a”,”click”,function() <
var a = new RegExp(‘/’ + window.location.host + ‘/’);
if(!a.test(this.href)) <
event.preventDefault();
event.stopPropagation();
window.open(this.href, ‘_blank’);
>
>);

Technically it’s a nice solution.

On the other hand it might tempt designers to use it whenever they can. NEVER open up a new window unless it is absolutely necessary or is a 100% user-friendly. Having all external links open up in a new window is neither.

For MooTools it’s very similar:

Good one. I think, this post describes good about it and a perfect solution too.

Can i have any code to popup an iframe content dynamically……..

@nachomaans
How can I have copied the code you given to section .But I am not sure If I follow this line:You then activate it in your pages by adding externallinks(); in your $(document).ready(function()<

Where can I use it?

BTW I tried it in my wordpress blog

I think my comment comes quite late with respect to this post but I have written a small jQuery plugin for the same based on knowledge gain my this post and my readings about jQuery plugin development in the last week or so. Please find the link to the plugin and associated post hope its upto the jQuery plugin development standards.

Regards,
Bilal Awan

A small optimization: since the RegExp doesn’t change , move it outside the loop so it is only defined (and compiled) once. No sense in redefining it on each loop occurrence.

Also, it’s worth noting that this only works if all internal links have a full absolute path. Since it compares it to the host name, each link must contain the host name. Relative links in the form /link/to/something or link/to/something will be treated as external links.

I forgot the dollar sign in my code snippet! Here is the correct code:

How to use this code?

I’m know nothing about jQuery, i just paste that code in HTML head, and i get this error in Chrome web inspector:

el Abee.. you have to first include the actual jQuery library and then, make sure the actual code you paste in is within tags and that those two tags are within the tags. And by the way, including jQuery needs to be done between the head tags too:

sir i have a problem that there are thumbnails in my page when a user clicks it i want to open the larger image of that thumbnail in a div new window tab

Excelente tip, gracias

Here is what we do:

and in the jQuery file we use:

I tried every variation I possibly could of using $(‘a[rel=”external”]) I could think of. I used double quotes, single quotes, tried using [rel^=”external”] in an attempt to just make the thing look for a link that begins with, I copied and pasted the code instead of typing it out. I made sure that arbitrary jQuery code would work in this scripts place. I made sure that my WordPress enqueue_script was working properly. I tried similar scripts from other websites. I’ve Googled til my fingers bled…

…and still nothing that involves using [rel=””] works for me. I’m using the latest jQuery library from the jQuery CDN (1.7.1 minified @ the time I’m writing this comment). Am I missing something? Does this version of jQuery not pick up on [rel=””]?

If I take the [rel=”external”] out, it works, but for every link (which is to be expected since there’s no conditional). I wrote something else that works that’s a derivative, but the [rel=”external”] just seems so much more elegant and I’d rather use that.

Here’s my script:

Just noticed one thing about the first line in my comment above. $(‘a[rel=”external”]) should be $(‘a[rel=”external”]’).

Any ideas on why this is happening? 🙁

Sorry, I could be wrong, but the examples shown here do not work if the attribute with the “external” there is some attribute, such as, “nofollow” or “author”. I used to blog a little bit different code, taken from the plugin:

Tried them all and couldn’t get them to work either…. that is till I tried the code from Konstantin, worked perfect and loaded super fast! Thank you thank you thank you…. saved much time and effort. Question: is it valid? Was usuing simple javascript before but was slow and clunky….(below).

Thanks again Konstantin.

This works great, but the code does interfere with some Google Analytics features. For instance, we lost all of our outbound link tracking when using this.

Оцените статью