Tuesday, November 29, 2011

drupal target _blank not working

A target="_blank" alternative for Drupal, or saving users' content by overriding the filter tips link
With a few lines of code in template.php and a small jQuery script, you can fix that by opening a new window when that link is clicked - without losing XHTML compliance (which you'd lose if you used target="_blank"). Additionally, you can re-use that trick elsewhere by adding a special class attribute to your anchor tags.

The first thing you need to do is add the following lines to your Drupal theme's template.php (replacing YOURTHEMENAME with your theme's name):

// Theming the filter tips more info link so users don't lose
// their stuff when visiting another page.
function phptemplate_filter_tips_more_info() {
  return '<p>'. l(t('More information about formatting options'), 'filter/tips', array('class' => 'target_blank')) .'</p>';
}

drupal_add_js(drupal_get_path('theme', 'YOURTHEMENAME') .'/target-blank.js', 'theme');



What that does is first override the theme function for the filter tips "more link" and add the "target_blank" class to that link. Our jQuery will use that class. Secondly, it tells Drupal to add a Javascript file called target-blank.js to every page. It's a really small script, and because of the potential for re-use, we might as well load it on every page, so we don't put any conditions on when we add it.
Next, create a file named target-blank.js in your theme's folder and add the following jQuery Javascript to it:

$(document).ready(function(){
  $("a.target_blank").click(function(){
    window.open(this.href);
    return false;
  });
});



This jQuery script waits until the document is ready, then on the click of any anchor tag with the class "target_blank" it opens that link in a new window.
That's it.
If you want to use this jQuery with any other anchor tags in your site, add class="target_blank" and you've got a link opening in a new window without compromising your XHTML compliance.
Hat tip to ejhildreth for the tip on using jQuery to maintain XHTML compliance.
Additionally, you can read about why this isn't in Drupal already. In short, opening new windows is considered bad UI. And I agree. My personal conviction, though, is losing users' data is worse.

No comments:

Post a Comment