How do I add a target="_blank" attribute to menu items?

smithaa02 - December 11, 2006 - 15:25

Basically, I want one of my menu items, to link to a new page, as opposed to opening in the present page. Is there a way to do this?

By theming

zigazou - December 11, 2006 - 15:36

The only way I can think of is to do it by theme in block.tpl.php.

You insert target="_blank" in each a tag that does not contain a link inside your site (everything unlike '/path/to/node' and 'http://www.yoursite.com/').

page.tpl

glendac - December 11, 2006 - 17:04

This thread (http://drupal.org/node/64892) might help show you what code and where to insert it in the page.tpl.php file of your site's theme. But most page templates deal only with the $primary_links and $secondary_links variables and might not cover menu items with external links that you want to create. You might have to look elsewhere to make changes. I'm looking into this myself and here are some Drupal theming pages that I'm looking at:

Use jQuery instead

Digital Spaghetti - December 11, 2006 - 17:02

Hey, instead of using target="" which breaks XHTML validation, use JavaScript instead.

Find out what the class or ID of your link is. For example, if it's menu-1-2 then use the below code:

<?php
drupal_add_js
('$(document).ready(function(){$("a.menu-1-2").click(function() { window.open(this.href); return false; }    ); } );', 'inline' );
?>

You can insert this in your template.php file.

not working?

Koen_Vanmeerbeek - July 24, 2008 - 11:31

Hallo,

I tried this code, but it doesn't seem to work... I use Drupal 5. Maybe something changed?

Koen

Seems to work in 6

bwoods - October 17, 2008 - 20:26

Although I'm not sure this is really preferable, considering that for any link that I need to open, I'll need to specify the ID/class separately. Furthermore, with the menu build, there's no guarantee that I'll have a unique ID/class to use, which seems a bit strange.

Try this

jetnet - January 20, 2009 - 23:19

Try this insted:

drupal_add_js ('$(document).ready(function(){ $(\'a[@href^="http"]\').each(function(){$(this).attr({ target: "_blank" });}); } );', 'inline' );

That will make ANY link that has begins with http, open in a target="_blank".

Great idea, but ...

bwoods - January 23, 2009 - 01:51

This doesn't seem to work with the pathauto module, since the generated links contain http.

target=_blank in primary links menu

jeffschuler - June 10, 2009 - 17:11

For adding target="_blank" to primary links menu items in Drupal 5 and 6, see Open link in new window.

The solution uses Drupal's menu_item_link theme hook.

 
 

Drupal is a registered trademark of Dries Buytaert.