Tag: new

Code Snippet – Open Link in New Window in Drupal 7

Although this is not recommended, I’ve seen the question mentioned in the topic come up a couple times over the last few weeks:

How do I get my links to open in a new window or tab in the user’s browser in Drupal 7?

I’ve heard that the target=”_blank” method is once again valid in HTML 5…however, it will still make your HTML fail validation under other specifications. The way around this is to use JavaScript.

Copy and paste this snippet into the appropriate area of your site – usually a JavaScript file in your theme. When you want to make a link open in a new window or tab, instead of target=_blank, add rel=”external”.

(function ($) {
Drupal.behaviors.externalLink = {
attach: function (context, settings) {
$('a[rel="external"]', context).attr("target", "_blank");
}
}
}(jQuery));

The reason this workaround is OK to use is that it does a little something called separating presentation from behavior. In other words, you aren’t relying on the browser to take a particular action because of the HTML itself; you’re telling it what action to take in the JavaScript.