Tom Lauck’s Deseloper.org

A Simple Modal – Redux

author:

Over a year ago I walked through an example of creating the basic foundation for a modal window using jQuery.  The goal was simplicity, minimalism, and flexibility to add-on functionality as needed.

As stated at the outset, this post was meant to illustrate a bare bones and simple example of a modal window. If you wanted to extend the functionality for example, it would be quite simple to [...] suit needs.

Last Year’s A Simple Modal Post

The example was well received in feedback from readers, and there was some constructive criticism as well. Equal to the amount of people that appreciated the minimalistic approach were requests from readers to support IE6, forms, and a host of other odds and ends.  Some readers had some useful feedback for features and additions that I purposefully did not include in an effort to keep things basic.

Therefore, I thought there was a nice opportunity to revisit the basic modal window script and make it a bit more comprehensive in an effort to suit the needs and requests of the aforementioned readers.  So before we get into the code, lets outline some things that have changed:

  • Converted for use as a jQuery plugin.
  • Added IE6 compatibility
  • Added Opera compatibility
  • Added ability to fade in and out
  • Added multiple ways of setting parameters
  • Added multiple content types (‘image’ and ‘iframe’)

View Example | Download Source

The Plugin

(function ($) {

	/**********************************
	* CUSTOMIZE THE DEFAULT SETTINGS
	* Ex:
	* var _settings = {
	* 	id: 'modal',
	* 	src: function(sender){
	*		return jQuery(sender).attr('href');
	*	},
	* 	width: 800,
	* 	height: 600
	* }
	**********************************/
	var _settings = {
		width: 800, // Use this value if not set in CSS or HTML
		height: 600, // Use this value if not set in CSS or HTML
		overlayOpacity: .85, // Use this value if not set in CSS or HTML
		id: 'modal',
		src: function (sender) {
			return jQuery(sender).attr('href');
		},
		fadeInSpeed: 0,
		fadeOutSpeed: 0
	}

	/**********************************
	* DO NOT CUSTOMIZE BELOW THIS LINE
	**********************************/
	$.modal = function (options) {
		return _modal(this, options);
	}
	$.modal.open = function () {
		_modal.open();
	}
	$.modal.close = function () {
		_modal.close();
	}
	$.fn.modal = function (options) {
		return _modal(this, options);
	}
	_modal = function (sender, params) {
		this.options = {
			parent: null,
			overlayOpacity: null,
			id: null,
			content: null,
			width: null,
			height: null,
			modalClassName: null,
			imageClassName: null,
			closeClassName: null,
			overlayClassName: null,
			src: null
		}
		this.options = $.extend({}, options, _defaults);
		this.options = $.extend({}, options, _settings);
		this.options = $.extend({}, options, params);
		this.close = function () {
			jQuery('.' + options.modalClassName + ', .' + options.overlayClassName).fadeOut(_settings.fadeOutSpeed, function () { jQuery(this).unbind().remove(); });
		}
		this.open = function () {
			if (typeof options.src == 'function') {
				options.src = options.src(sender)
			} else {
				options.src = options.src || _defaults.src(sender);
			}

			var fileExt = /^.+\.((jpg)|(gif)|(jpeg)|(png)|(jpg))$/i;
			var contentHTML = '';
			if (fileExt.test(options.src)) {
				contentHTML = '<div class="' + options.imageClassName + '"><img src="' + options.src + '"/></div>';

			} else {
				contentHTML = '<iframe width="' + options.width + '" height="' + options.height + '" frameborder="0" scrolling="no" allowtransparency="true" src="' + options.src + '"></iframe>';
			}
			options.content = options.content || contentHTML;

			if (jQuery('.' + options.modalClassName).length && jQuery('.' + options.overlayClassName).length) {
				jQuery('.' + options.modalClassName).html(options.content);
			} else {
				$overlay = jQuery((_isIE6()) ? '<iframe src="BLOCKED SCRIPT\'<html></html>\';" scrolling="no" frameborder="0" class="' + options.overlayClassName + '"></iframe><div class="' + options.overlayClassName + '"></div>' : '<div class="' + options.overlayClassName + '"></div>');
				$overlay.hide().appendTo(options.parent);

				$modal = jQuery('<div id="' + options.id + '" class="' + options.modalClassName + '" style="width:' + options.width + 'px; height:' + options.height + 'px; margin-top:-' + (options.height / 2) + 'px; margin-left:-' + (options.width / 2) + 'px;">' + options.content + '</div>');
				$modal.hide().appendTo(options.parent);

				$close = jQuery('<a class="' + options.closeClassName + '"></a>');
				$close.appendTo($modal);

				var overlayOpacity = _getOpacity($overlay.not('iframe')) || options.overlayOpacity;
				$overlay.fadeTo(0, 0).show().not('iframe').fadeTo(_settings.fadeInSpeed, overlayOpacity);
				$modal.fadeIn(_settings.fadeInSpeed);

				$close.click(function () { jQuery.modal().close(); });
				$overlay.click(function () { jQuery.modal().close(); });
			}
		}
		return this;
	}
	_isIE6 = function () {
		if (document.all && document.getElementById) {
			if (document.compatMode && !window.XMLHttpRequest) {
				return true;
			}
		}
		return false;
	}
	_getOpacity = function (sender) {
		$sender = jQuery(sender);
		opacity = $sender.css('opacity');
		filter = $sender.css('filter');

		if (filter.indexOf("opacity=") >= 0) {
			return parseFloat(filter.match(/opacity=([^)]*)/)[1]) / 100;
		}
		else if (opacity != '') {
			return opacity;
		}
		return '';
	}
	_defaults = {
		parent: 'body',
		overlayOpacity: 85,
		id: 'modal',
		content: null,
		width: 800,
		height: 600,
		modalClassName: 'modal-window',
		imageClassName: 'modal-image',
		closeClassName: 'close-window',
		overlayClassName: 'modal-overlay',
		src: function (sender) {
			return jQuery(sender).attr('href');
		}
	}
})(jQuery);

As you can see, quite a bit has changed – which is not necessarily a bad thing.  There is now tighter integration with jQuery and more out of the box configuration ability as a result.

Adding Some Style

.modal-overlay {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	height: 100%;
	width: 100%;
	margin: 0;
	padding: 0;
	background: #131313;
	opacity: .85;
	filter: alpha(opacity=85);
	z-index: 101;
}
.modal-window {
	position: fixed;
	top: 50%;
	left: 50%;
	margin: 0;
	padding: 0;
	z-index: 102;
	background: #fff;
	border: solid 8px #000;
	-moz-border-radius: 8px;
	-webkit-border-radius: 8px;
}
.close-window {
	position: absolute;
	width: 47px;
	height: 47px;
	right: -23px;
	top: -23px;
	background: transparent url(../images/close-button.png) no-repeat scroll right top;
	text-indent: -99999px;
	overflow: hidden;
	cursor: pointer;
}

Implementation

<a href="modal.html" onclick="$(this).modal({width:833, height:453}).open(); return false;">Modal iFrame</a>
<a href="images/your-image.jpg" onclick="$(this).modal({width:500, height:375}).open(); return false;">Modal Image</a>

Although a little more weight has been added to the script itself, the implementation is more flexible and can be used with just about any jQuery chain – whether its onclick, a document being loaded, you name it.  There is also an added ability to set parameters in your area of choosing – inside the CSS, in the plugin itself, or in the method call or jQuery chain object.

Moving Forward

So if you are looking for something extra simple, head on over to last years post and in the meantime enjoy the added functionality with this updated example.

View Example | Download Source

Oct 21 2009

It’s the Age of the Deseloper

author:

Having a non-conventional title to this journal has been somewhat of an interesting journey.  The responses regarding the title always vary and are at times, very amusing.  Surprisingly enough, about three (3) times out of ten (10), informal interviewees cannot decipher the meaning of deseloper within a reasonable 30 seconds.  Ironically, the percentage of users that did not immediately grasp the word deseloper is about 30%.  This is in fact roughly the same percentage of users that still use IE 6.  While I blatantly discriminate against IE 6 and its users, I do not and will not discriminate against users who not understand the word deseloper.  So to add a portion of understanding to all of my readers and for general education purposes, I thought it would be beneficial to examine what exactly a deseloper is in today’s workplace and if they truly have value.

Definition of Deseloper:
  • one who has the ability to produce both web design and development at high fidelity.

To dive a little deeper, deselopers can go one of three ways in there area of focus, either favoring the left side of the brain, the right, or more of a balanced approach.  Typically, these individuals can do it all.

How do you go about creating the design (look & feel, user experience, information architecture) of your applications?

  • I do it myself 58.6%

InsideRIA

As one can imagine, this is extremely valuable in small or freelance settings.  In a larger corporate setting is there still value?

At first pass the answer may be no.  Typically large corporate environments have two sides of the house, design and development or IT.  A designer or developer having an understanding of the other side becomes more of a bonus rather than a requirement.  However, with the emergence of sophisticated UI technologies such as Flex, Silverlight, AJAX, should leveraging these technologies be left to the designer or developer?

I would argue to say both.  Take for instance the continual drive to allow better separation of logic and presentation in Silverlight. Flex, or AJAX.  This is evident by the many Microsoft developers exited over Sliverlight, but are not ready to be Silverlight developers. If there is a Silverlight developer, they are faced with the serious lack of Silverlight designers. Therefore, in order to execute on a Silverlight app, either a designer has to learn XAML and C# or the developer has to try be a designer. And we all know how that usually turns out. So, we find ourselves in an area where the true separation of developers and designers for these front end or UI technologies has not happened yet.  Enter the deseloper.

Until an adoption of these front end technologies happens for application developers around the world, or designers learn how to effectively use the other side of their brain and produce rock solid code, there is a valuable niche for the deseloper.  Because customers, clients, or management is always looking for the latest and greatest, deselopers are willing and ready to execute.  So perhaps the deseloper may someday in the near or far future be a rich internet application developer or rich internet application designer (as opposed to web designer or web developer).

On estimating value in the workplace :

A skilled, quick professional stands out these days. The people who shine are the people who get the new world – a no nonsense approach, courtesy, and most importantly, speed.

ReadWriteWeb

The deseloper gets the new world.  And with a full grasp of all the tools on hand from both a design and development standpoint, the deseloper can strike like lightning.  Yes, in whatever title or role the deseloper is morphed into, the deseloper is certainly here to stay.

Mar 16 2009

Heading off to <head>

author:

Tomorrow is the start of the <head> conference, and yes I am lame and used <head> as a pun.

Earlier this week I was somewhat unsure of how everything was going to shape up.  After all, I have never been to an online conference.  Upon looking at some of the sessions lined up today I was pretty stoked.  On an equally positive note, how awesome is it not to have to fly anywhere, stay at an overpriced hotel, or pay an exorbitant amount to attend a 3-day sales pitch.

<head> looks like it is shaping up to eliminate all of those headaches.  If you haven’t had a chance check it out, it can’t hurt for $149.

Official website: http://www.headconference.com

Oct 23 2008

RIA Myth Busting: Back Button, History, and SEO

author:

I have touched on the topic of SEO in the past, however, that article the focused on a broad range of ideas to improve organic search.  I wanted to focus in on realities surrounding RIAs and commonly requested features, specifically to the combination of back button support, bookmarking, and search engine optimization.  All of these features would be wonderful in a single page interface, and with current technology and methodology, is it possible to have our cake and eat it too?

It is important to first have an understanding of the difference in objectives between a web application and a web site.  (Technically speaking, most web sites are web applications, but we are using the term in a looser sense).  Typical examples of an application in this scope would be GMail, Google Reader, and the user section of Mint.com – sites with almost no need of searchable content.  Examples from the opposite end of the spectrum would be Bloomberg, A List Apart, Wired, and someone’s blog.  Therefore, we have two camps, one where the sole focus is on interaction with data and no search strategy is needed and the other dictates a solid search strategy.

A method that has been gaining steam in the RIA world is using a hash sign (#), or anchor, in the URL.  Many talented people have spent precious time creating solutions to history and back button support for AJAX and Flash applications.  This is fantastic for a web application, because it provides capability for standard user interactions supported in browsers that are typically unsupported in rich internet applications.

So now that there is history support, does that mean SEO has been fully considered?  An article I found on w3.org sheds some light on the subject using a CNN video player as a case study:

CNN uses links like the above for all the topical video segments that are published on its site. The URL in this case has the following components:

Component Value
Protocol http
Host www.cnn.com
Path video
Client Param #/video/tech/2008/02/19/vo.aus.sea.spider.ap

2.1.1 Things To Note

The browser is expected to do a GET of the URL leading up to the fragment, and the processing application, in this case, the JavaScript embedded in the HTML Response processes the portion of the URL following the #.
The fragment identifier has been intentionally identified as a client parameter.
Treating it as a regular fragment identifier in this usage would result in one incorrectly infering that the URL for the video resource being addressed is http://www.cnn.com/video.
This would result in all the video links on the CNN site getting the same URL.
Thus, the entire URL in this case is http://www.cnn.com/video/#/video/tech/2008/02/19/vo.aus.sea.spider.ap
A consumer of this URL who goes looking for an idwithin the Response that matches the #-suffix of this URL will fail.
The reported Content-Type for the resource is text/html. However the behavior of the #-suffix in this case is not defined by the HTML specification.
As used, the #-suffix is a first-class client parameter in that it gets consumed by a script that is served as part of the HTML document returned by the server upon receiving a GET request.
This embedded script examines the URL available to it as script variable content.location, strips off the # and uses the rest of the prefix as an argument to function that generates the actual URL.
Having constructed this content URL, the script then proceeds to instruct the browser to play the media at the newly constructed location.

Notice that “the browser is expected to do a GET of the URL leading up to the fragment…JavaScript embedded in the HTML Response processes the portion of the URL following the #.”  To paraphrase, Google does not look at client side interactions, the fragment is truncated from Google’s index.  From this several assumptions can be made:

  1. Any back link using http://example.com/#example is actually viewed as http://example.com
  2. Back links pointing to URL fragments will have no individual page rank.
  3. In content rich scenarios, the use of URL fragments in leu of separate pages effectively dilutes almost all search traction.

Reflecting on how Google treats URL fragments, it can be clearly seen that a single page interface is not an effective strategy in scenarios with rich content.  Another big myth around single page interfaces is in the use of Flash, SWFAddress and/or Flex’s history manager.  Google will disregard URL fragments, the very foundation of SWFAddress and Flex’s history manager.  To reiterate, Googlebot just disregarded the URLs you have just crafted with SWFAddress.  It should be stated that some individuals wholeheartedly believe that using URL fragments is a successful SEO strategy.  Yet, when Google is typically the number one returning visitor, do you really want to take a chance at questioning the very foundation Google uses to spider your site?

Take for instance a designer’s personal site with tabs for Home, Resume, Portfolio, and Contact.  Would the designer want to implement a single page interface?  The answer would likely be no.  The content would gain more traction if it is separated properly.  To rehash the example of Google Reader, a single page interface is a good choice, for Google Reader would not benefit from having a separate page for each feed a user is subscribed to.

The advances made in RIA with regard to history and back button support encapsulate the innovative spirit that the web has embraced.  However, web workers tend to jump on bandwagons and this filters down to individuals with the power to poorly implement a technology – remember Flash intro pages?  Much like a seasoned web worker becomes very business and client savvy after years in the field, we need to be Google savvy.  Threfore, next time a wirefrime for a single page interface lands your desk, does the content dictate a search strategy?  If so, do some research on the reality of the solutions and ultimateley be kind to Google and Google will be kind to you.

Oct 22 2008

A Simple Modal

author:

Updated – Version Available

A Simple Modal – Redux

[See a demo here]

Modal windows seem to be the rage these days and somewhat synonymous with “Web 2.0.” And yes, options exist, whether it be Lightbox, Thickbox, or .NET AJAX — to name a few. Recently, Facebox has emerged as a very promising contender. The aforementioned plugins/widgets have proven their usefulness to many developers during their life course. In fact they one might even go so far as to deem “standard” to the plugin of choice.

Yet, what if a scenario arises where you do not need such full featured capability? After all, most of the plugins out there come with their own CSS along with the JavaScript. This is not to say that CSS wouldn’t be necessary if one were to create a homegrown solution. The fact remains that their is still integration work involved.

Therefore, my aim in this post is to illustrate a simple example of leveraging the jQuery framework to create a simple iFrame modal window. Of course a polished plugin will be more robust, however, robust is at times overkill. It is at that point where simplicity comes into play and thus the forthcoming example.

Defining the Basics

First we create an object in JavaScript to encapsulate some core methods and properties that we could potentially reuse.

var modalWindow = {
	parent:"body",
	windowId:null,
	content:null,
	width:null,
	height:null,
	close:function()
	{
		$(".modal-window").remove();
		$(".modal-overlay").remove();
	},
	open:function()
	{
		var modal = "";
		modal += "<div class=\"modal-overlay\"></div>";
		modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
		modal += this.content;
		modal += "</div>";	

		$(this.parent).append(modal);

		$(".modal-window").append("<a class=\"close-window\"></a>");
		$(".close-window").click(function(){modalWindow.close();});
		$(".modal-overlay").click(function(){modalWindow.close();});
	}
};

Notice that only three CSS classes need to be defined, “.modal-window”, “.modal-overlay”, and “.close-window”. Because of the fact that we are trying to keep things simple, I’ve decided not to check to null’s in required properties (windowId, content, width, height).

Basic Design

Next the three classes from above need to be defined. The “.modal-overlay” class is the layer that covers the current view and serves as a backdrop for the modal window. “.modal-window” is obviously the window itself. In this case, the modal-window class is very generic since we will rely on the styling in the transparent iFrame for design. Lastly, I chose to implement a close graphic which is displayed using the “.close-window” class. Again, this is very basic.

.modal-overlay
{
	position:fixed;
	top:0;
	right:0;
	bottom:0;
	left:0;
	height:100%;
	width:100%;
	margin:0;
	padding:0;
	background:#fff;
	opacity:.75;
	filter: alpha(opacity=75);
	-moz-opacity: 0.75;
	z-index:101;
}
.modal-window
{
	position:fixed;
	top:50%;
	left:50%;
	margin:0;
	padding:0;
	z-index:102;
}
.close-window
{
	position:absolute;
	width:32px;
	height:32px;
	right:8px;
	top:8px;
	background:transparent url('/examples/modal-simple/close-button.png') no-repeat scroll right top;
	text-indent:-99999px;
	overflow:hidden;
	cursor:pointer;
	opacity:.5;
	filter: alpha(opacity=50);
	-moz-opacity: 0.5;
}
.close-window:hover
{
	opacity:.99;
	filter: alpha(opacity=99);
	-moz-opacity: 0.99;
}

The Grand Opening

Now that we have set some basic styles and defined our core functionality, we can open a new modal window to display our iframe.

var openMyModal = function(source)
{
	modalWindow.windowId = "myModal";
	modalWindow.width = 480;
	modalWindow.height = 405;
	modalWindow.content = "<iframe width='480' height='405' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>";
	modalWindow.open();
};

Implement

<a href="/example/modal-simple/modal.html" target="_blank" onclick="openMyModal('/example/modal-simple/modal.html'); return false;">Click here to open</a>

Implementation is simple, just make a call to the method created earlier with the source of the modal window.

Beyond Simple ‘Modaling’

As stated at the outset, this post was meant to illustrate a bare bones and simple example of a modal window. If you wanted to extend the functionality for example, it would be quite simple to create more “openMyModal” methods to suit needs. So if Facebox or Thickbox are too much for your application, why not try the simple approach?

Updated – Version Available

A Simple Modal – Redux

Apr 25 2008

« Older Entries