Skip to content

Instantly share code, notes, and snippets.

@MidnightLightning
Last active September 26, 2015 00:38
Show Gist options
  • Save MidnightLightning/1011074 to your computer and use it in GitHub Desktop.
Save MidnightLightning/1011074 to your computer and use it in GitHub Desktop.
Javascript popups

The "target" attribute in links is now only used for pages using framesets (reference), so how do you pop up a new browser window for links you want to have people navigate to without leaving your page?

Using the current W3 standard for anchor tags anchor tags can be given a rel attribute that describes what relation the linked-to page has to this current page. It also provides a standard list of available relationships. Many other groups added to this list and there are many widely-used values for the rel tag, including "external".

With this method, give links to be made popups a rel attribute of "external", and include the following file in the head of the document.

// Function to parse all anchor tags, and automatically make those that have a class of 'newWin' open in a new window
var parsePopups = function() {
var x = document.getElementsByTagName("a");
for (var i=0; i<x.length; i++) {
if (x[i].rel.indexOf('external') > -1) {
// This anchor is an external one
x[i].onclick = function() {
newWin = window.open(this.href, 'mysite_pop'); // Pop a new window
if (window.focus) { newWin.focus() } // Focus on it if possible
return false; // Keep from following standard href of link
}
}
}
}
window.onload = parsePopups; // Standard initialize
$(document).ready(function() {
$("a[rel*='external']").click(function(event) {
event.preventDefault(); // Keep from following standard href of link
new_win = window.open($(this).attr('href'), 'offsite_popup') // Pop up a window to that URL
if (window.focus) { new_win.focus() } // Give it focus if possible
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment