Archive for month: June, 2011

jQuery External Links – Open in New Window

Categories: CSS, HTML, javascript, jQuery

When it comes to website management links are huge. Most people realize that if they have a link off their site that it is a possibility that they will loose person. Now, if the goal for your website it to keep customers where they can buy from you, it makes sense to never send a customer away.

However, the web is an amazing place with a huge amount of information. Your site can’t have all the info. Also, linking to quality content will also improve your SEO. So, you might just end up with more people visiting your site if you share the wealth around a little. But how can you have your cake and eat it too? Well, you could open a new browser window when you were sending someone to another site. That would mean that when they closed that windows, your site would still be there. Just so they don’t get lost.

Today, I am going to produce some code that will automatically open a new window for any external link and also show you how to dress up these links so that people will know that they are going to take them off your site. Hopefully, it will be a useful tutorial in some of the great features built right into jQuery.

1jQuery Selectors
jQuery has some amazing capabilities when it comes to its built in selectors for html elements. In this case, it makes good sense to use a selector to get all the links on the page and then use the jQuery each() function to iterate through each found link and test it to see if it links to an external site.

We’ll test if the link’s hostname matches the pages hostname. If they don’t we’ll know that the link is to another site and then we can do some additional work on it. The code looks like this:

2Alter The External Link
I want to add a new class to each external link (I’ll cleverly call this class ‘externalLink’). We’ll use the jQuery .addClass() function. We’ll use the .click() function to modify the existing onclick event for the link. Note: we could have added a target=”_blank” attribute, but that would not be xhtml compliant. These can be chained onto one line for efficiency.

jQuery(this).click(function(event) {
     event.preventDefault();
     event.stopPropagation();
     window.open(this.href, '_blank');
}).addClass('externalLink');

At this point the code is also complete. We want this code to fire when the page loads. So, we will wrap the code in the jQuery .ready() event handler. There is a shorthand that is great, we’ll use it here.

$(function() {
 // Handler for .ready() called.
});

Lastly, I wanted to style the external links differently from all the other links. We have already added the new class, ‘externalLink’, to the link element. I wanted to add an icon similar to how Wikipedia does. So, we’ll want to add a couple lines of css to the styles.

3Putting It All Together
When we put it all together it is a simple, elegant and extremely useful solution. Here is the final code:

$(function() {
   $("a[href*='http://']:not([href*='"+location.hostname.replace
           ("www.","")+"'])").each(function() {
       $(this).click(function(event) {
             event.preventDefault();
             event.stopPropagation();
             window.open(this.href, '_blank');
        }).addClass('externalLink');
   });
});
.externalLink {
    background: url("/images/externalLink.png") no-repeat scroll right center transparent;
    padding-right: 13px;
}

jQuery Lightbox

Categories: code, javascript

So, the other day I was building a popup dialog box based on the principals seen in most light boxes. I wanted the box to be centered top and bottom and left and right. The obvious choice was to use jQuery, but I wanted something that would be reusable.

Seemed like there were 3 parts to the problem.

  1. Center the dialogue box
  2. Grey out the background
  3. Hide all of the lightbox when someone clicks off the lightbox

1 Centering the dialogue box
I found a start at Stack Overflow, while a great start, it seemed to be missing a few things that I was looking for.

jQuery.fn.UnseenCenter = function() {
	this.css({
		"position": "absolute"});
	this.css({
		"top": (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px",
		"left": (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"
	});
	return this;
};

The code extends the jQuery Framework and creates a new function called ‘UnseenCenter’ that can be called in association with any element on the page. Note: when getting calculating the element’s size we are using the jQuery outerHeight() and outerWidth() to insure that we are taking padding and margins into account.

For the box itself, we can use a div that is styled with CSS. Now, we want to insure that the jQuery code is unobtrusive so we will use classes and ids to manage onClick() events that show and hide the lightbox. In this case I chose a class called ‘UnseenLightbox’ that will be used to associate and element with the click event.

To enable multiple lightboxes on the same page we need to create some code that will allow us to target specific lightbox content with the click() event. To do that I created a class/ID hi-bred solution. Every element that has the class ‘UnseenLightbox’ will also have a class with a particular format ‘UnseenTarget-DivID’ where the ‘DivID is the id of the lightbox element to be displayed.

Here is the HTML so far:

<a href='#' class='UnseenLightbox UnseenTarget-DivID'>click here for lightbox</a>
<div id="DivID" class='Unseenlightbox-content' style="display:none;">
	You can put anything here:
	<ol>
			<li>Images</li>
			<li>Lists</li>
			<li>Forms</li>
	</ol>
	Use CSS to make this look great!
</div>

We’ll use the $(document).ready(handler) to run through the dom when loaded and connect the onClick events for each of the elements to the targeted lightbox content. To do that, we’ll look at each ‘UnseenLightbox’ classed element and check that it has a ‘UnseenTarget-DivID’ class. If it does, we have all the information we need to set an onClick event targeting the correct lightbox div. It looks like this:

$(function() {
	$('.UnseenLightbox').each(function(index) {
		$(this).click(function() {
			targetDivID = null;
			$.each($(this).attr('class').split(' '), function(index, item) {
				if (this.indexOf("UnseenTarget-") === 0) {
					targetDivID = item.replace('UnseenTarget-', '');
				}
			});
			if (targetDivID != null) {
				$('#' + targetDivID).UnseenLightboxShow();
			}

		});

	});

});

2 Greying the background
This is one of these things that is useful to make sure the user focuses on the dialogue and does not get distracted. We’ll also make it so that if the user clicks on the greyed background that the dialogue will close. We’ll do this with a div that we’ll .append() to the dom with jQuery. We can check to insure we only do this once by checking to see if the element exists in the dom.

jQuery.fn.exists = function() {
	return jQuery(this).length > 0;
}
if (!$('#UnseenBackgroundDiv').exists()) {
	$('body').append('<div id="UnseenBackgroundDiv">');
}</div>

Now that we have the background div in the dom, we’ll want to place it so that it covers the whole background. We’ll do that by setting the some CSS attributes with the jQuery .css() function. We’ll need to know how large the document is. We can use $(document).height() and $(document).width() to get that. We are going to want to absolute position the background and set its z-index so that it will be over everything but the lightbox.

Now, just so that it is pretty, we can use the .fadeTo(), .fadeIn(), and .fadeOut() effect functions from jQuery. We can use these on the targeted content div as well as the grey background.

jQuery.fn.UnseenLightboxShow = function() {
	if (!$('#UnseenBackgroundDiv').exists()) {
		$('body').append('<div id="UnseenBackgroundDiv">');
		$('#' + 'UnseenBackgroundDiv').click(function() {
			$(this).UnseenLightboxHide();
		});
	}
	$('#' + 'UnseenBackgroundDiv').hide();
	$('#' + 'UnseenBackgroundDiv').css({
		"top": 0,
		"left": 0,
		"height": $(document).height() + "px",
		"width": $(document).width() + "px",
		"position": "absolute";
		"background-color":"black",
		"z-index": "9000"
	});
	$(this).css("z-index", '9100');
	$('#' + 'UnseenBackgroundDiv').fadeTo('slow', .7, function() {});
	$(this).fadeIn('slow', function() {}).center();
};</div>

3 Close the Lightbox
Most of the heavy lifting is complete. We’ll create just one more jQuery function called ‘UnseenLightboxHide’ that when called will fade all the lightbox elements out. We’ll also need to add some code to call the function when someone clicks on the background.

jQuery.fn.UnseenLightboxHide = function() {
	$('#' + 'UnseenBackgroundDiv').fadeOut('slow', function() {});
	$('.Unseenlightbox-content').fadeOut('slow', function() {});
}
$('#' + 'UnseenBackgroundDiv').click(function() {
	$(this).UnseenLightboxHide();
});

Conclusion

I hope this tutorial was helpful. There are a couple interesting problems we solved today. Something we did not implement that would be very helpful would be a quick couple of lines that would recenter the lightbox when someone resizes the browser window. It would be fairly easy to refactor the code and implement jQuery’s .resize() function.

Demo and Files

You can look at a quick demo can be found at Lightbox Demo.

The javascript file can be found Here.

© 2012 - www.UnseenRevolution.com - Unseen Revolution LLC. 333 NW 4th Ave. Portland, OR 97209
5094aab3d19c5
By
UnseenRevolution.com Portland, OR Category: Webinar
UnseenRevolution.com Portland, OR Category: Webinar
UnseenRevolution.com Portland, OR Category: Webinar