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?
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
The only way I can think of is to do it by theme in block.tpl.php.
You insert
target="_blank"in eachatag that does not contain a link inside your site (everything unlike '/path/to/node' and 'http://www.yoursite.com/').page.tpl
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
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:
<?phpdrupal_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?
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
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
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 ...
This doesn't seem to work with the pathauto module, since the generated links contain http.
target=_blank in primary links menu
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.
Here is the solution ;-)
http://drupal.org/node/335853#comment-2278626