Robust popup links in Drupal 6
Once MIDI files were reliably playing in the browser (see the previous post), the next thing I wanted was to have them play in little popup windows, instead of making a blank new page and playing there. Having to hit the browser's "Back button" after playing any MIDI was not acceptable.
The first way I did this was to put the Javascript code to make the popup window inside the link (with an onclick attribute). The problem with that method is that the link is completely broken when Javascript is not supported. Clearly a new page to play the file is the best option when Javascript is not supported.
So, the question is, how can one get a popup when Javascript is supported, but have the link still go to a new page and load the file when it is not?
The answer is to use Javascript (and the JQuery library) to make an appropriately tagged link popup if Javascript is fully supported, otherwise do nothing.
The first step is tagging the link. In my case, I'm using FileField for the MIDI file links so I overrode the theme_fiefield_file in the template.php of my composers_village_theme:
* Theme function for the 'generic' single file formatter.
*/
function composers_village_theme_filefield_file($file) {
...
if ($file['filemime']=='audio/midi') {
// mark MIDI link so that the javascript script.js can find it
// and make a popup-window
$options['attributes']['class'] = 'popup-link';
}
return '<div class="filefield-file clear-block">'.
$icon . l($link_text, $url, $options) .'</div>';
}
The next step is to implement the Javascript. This was a little tricky, for reasons noted at http://api.drupal.org/api/file/developer/topics/javascript_startup_guide.... Another starting point is http://drupal.org/node/121997. But what actually oriented me was the introductory JQuery material in Matt Butcher's book Learning Drupal 6 Module Development. The easiest way was to put the following code in a file called script.js in my composers_village_theme:
$(document).ready(function(){
$("a.popup-link").click(function() {
window.open(this.href, "popup", "width=250,height=50,menubar=0,toolbar=0,resizable=1,scrollbars=0");
return false;
});
});
};
- This line checks that Javascript is fully supported for Drupal.
- This line waits for the document to be fully loaded.
- This jQuery line adds a click handler popup to links of class "popup-link"
- This line actually creates the popup window.
For more information, consult references, but this recipe may get you started. It's what worked for me.
