Image popups with jQuery

I just finished some jQuery scripting with the following requirements:

1.) If the source attribute of an image tag contains x_small we need to open a new popup window with a bigger version that will be named x_big.jpg.

2.) The cursor needs to change to the pointing hand on mouse over to indicate to the visitor that something will happen if she clicks the image in question.

3.) The new popup window needs to resize itself to match the size of the opened image.

Popup Window with jQuery

The reason we are not using Ajax for this is that I’m starting to get fed up with it. I’m virtually sitting in the jungle with a crappy GPRS connection. It’s amazing how frustrating it is when all sorts of services are stalling because an Ajax request is taking its time. Gmail is the worst example (and yes I know about the HTML version, I’m using it more and more often).

In this case the new big image will simply open in a new window and the visitor can calmly continue to navigate the site without being stalled when it loads. Ironically I found an old school script that will accomplish this time tested behavior, works like a charm.

The document ready function in asd.js now looks like this:

$(document).ready(function(){
...
	$("img[src*='_small.']").css('cursor', 'pointer').click(function(){
		var img_name = $(this).attr('src').match(/\/(\w+)_small/i);
		var img_url = 'http://asiandivingvacation.com/assets/images/' + img_name[1] + '_big.jpg';
		popImage(img_url, $(this).attr('title'));
	});
});

The first selector will return a collection of all image tags containing a src attribute which in turn contains the sub-string _small. We continue by adding the cursor: pointer style to the collection and assign the onClick function.

The first regex match will return an array where the first item contains the whole matched expression, i.e. /dd_small.jpg in our case. The second item will contain the sub-match (\w+) which is dd of course, that is why we use img_name[1] to get dd_big.jpg.

Finally we use popImage() I linked to above to open the popup window. The function takes the path to the image to open and a second argument that will determine the title of the new window. We use this opportunity to grab the title attribute of the image tag and pass it along to create a relevant title.

Click the thumbnail above to see a screenshot of the result or browse to the live site (still very much under construction). Click on the first image of Donald Duck Bay to the right to get the popup.

Related Posts

Tags: , , , ,