01 April 2011

Create a new window using custom jQuery function

For my current project, I needed to pop up a new window from specific anchor tags on the page. This provided the perfect opportunity to write some custom jQuery to handle this. I started with some research into creating jQuery function; Jeremy Martin's blog post got me started. Next, I got some inspiration from this popup window generator, though I could never get it working for my site.

So the jQuery function looks like this:
/*
* Add a function to jQuery to automate popup windows.
*/
(function($){
$.fn.popWindow = function(options) {

// Declare some default values.
var defaults = {
width: 729,
height: 529,
left: 19,
top: 19,
location: 0,
directories: 0,
status: 0,
toolbar: 0,
menubar: 0,
resizable: 1,
scrollbars: 1,
url: '',
name: 'cms_win',
center: 0
};

// Merge the defaults with the options parameter.
var options = $.extend(defaults, options);

// For each of these objects...
return this.each(function(){
// Get a handle to this HTML object.
obj = $(this);

// Set the left and top if we're centering.
if (options.center){
options.left = (screen.width - options.width)/2;
options.top = (screen.height - options.height)/2;
}

// If user provided a URL, use that; otherwise use the HREF.
var url = (!jQuery(options.url).isEmpty()) ?
options.url : obj.attr("href");

// Concatenate the window.open() function's options.
var features = "width="+options.width+",height="+
options.height+",left="+options.left+",top="+
options.top+",location="+options.location+
",directories="+options.directories+",status="+
options.status+",toolbar="+options.toolbar+
",menubar="+options.menubar+",scrollbars="+
options.scrollbars+",resizable="+
options.resizable;

// Add an onClick() handler to this object.
obj.click(function(){
// On click, open a new window with these arguments.
window.open(url,options.name,features);
return false;
});
});
}
})(jQuery);

/*
* Add a function to jQuery to check null/undefined/blank
* status of object.
*/
(function($){
$.fn.isEmpty = function(){
return (typeof $(this) === "undefined" ||
$(this) === null ||
$(this) === "") ? true : false;
}
})(jQuery);
Note the helper function isEmpty() which serves to check for null, undefined, or blank variables. The folks on StackOverflow.com helped with that function. To use the popWindow() function, ensure you've included the latest jQuery library on your page; add the above code in a script tag; then set the style class on your anchor tag or add an ID so you can reference the object; finally, call it on your page like this:
jQuery(document).ready(function(){
// Set all the objects with pop class to open in new window.
jQuery(".pop").popWindow({
center: 1
});
});
In this case, I'm also taking advantage of the built-in center functionality to center the new window.

No comments: