Archive for category: jQuery

WordPress Tutorial: Load the jQuery Library from CDN

Categories: jQuery, SEO, Wordpress

Some might say there is really just 1 thing to remember about making good WordPress website. Make it fast. Speeding up your WordPress site will improve user experience and also improve your sites SEO. Using a CDN to distribute your jQuery library is a great place to start.

There are at least 4 reasons you should use a CDN to service jQuery on your page:

  • 1Decreased Latency
    Content Delivery Network — distributes your static content across servers in various physical locations. The User’s download will automatically target the closest available server in the network.
  • 2Increased parallelism
    To avoid needlessly overloading servers, browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.
  • 3Better caching
    Potentially the greatest benefit of using the Google AJAX Libraries CDN is that your users may not need to download jQuery at all. If your user had downloaded the content in the past, it may already be cached.
  • 4Reduced bandwidth costs
    If someone else’s CDN is pushing the content to your users, they are using their bandwidth, not yours.

All of these reasons add up to fast responsive websites. That may be the one thing that everyone agrees is a good thing.

WordPress: Google’s jQuery CDN

I spend a good amount of time working in WordPress environments. Seems like every theme comes with jQuery and the all use the local copy, obviously that is not a great idea, luckly there is a simple way to correct this oversight with just 6 lines of code.

function jquery_cdn() {
   if (!is_admin()) {
      wp_register_script('jquery', '', false, '1.7.2');
add_action('init', 'jquery_cdn');

Other jQuery CDN options

While I recommend using the Google CDN because it is so widely used and therefore increases the changes it will already be in your user’s cache, there are several other options.
Google’s jQuery CDN

Microsoft’s jQuery CDN

jQuery’s CDN

Other jQuery CDN Version Options

Most of the CNDs listed above will also service other versions of jQuery. For example if you wish to use jQuery 1.5.2 from Google’s CDN it is simply a matter of requesting

jQuery $(document).ready() shorthand – domready

Categories: javascript, jQuery

jQuery .ready()

JavaScript provides the load event for executing code when a page is rendered. This event gets triggered when the download assets such as images has completed. However, most people want their script to run as soon as the DOM hierarchy has been fully constructed. jQuery provides the .ready() for just this purpose. This is the corresponding domready function in Mootools.

$(document).ready(function() {
  // your code
  alert('Page: ' + $('title').html() + ' dom loaded!');
$(function() {
 // Handler for .ready() called.
 alert('Page: ' + $('title').html() + ' dom loaded!');
(function($) { 
  $(function() {
   // by passing the $ you can code using the $ alias for jQuery
   alert('Page: ' + $('title').html() + ' dom loaded!');

.ready() Handler

The handler passed to .ready() is guaranteed to be executed after the DOM is ready. This is usually the best place to attach all other event handlers and run other jQuery code. If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

jQuery Ajax Post

Categories: AJAX, javascript, jQuery

jQuery provides a quick, robust and easy way to request data from the server without a page reload through AJAX. In this short article we’ll look at loading data from the server using a HTTP Post Request.

jQuery $.post function

There is a shorthand AJAX post function with the following signature:

  url: 'myTargetURL.php',
  data: data,
  success: success function(data, textStatus, jqXHR),
  dataType: dataType

jQuery $.ajax Post Function

I prefer to use the default .ajax function for ease of use and maintainability.

type: 'POST',
url: 'myTargetURL.php',
data: data,
success: success function(data, textStatus, jqXHR),
complete: function(),
dataType: dataType
You’ll notice that they both accomplish the same thing, however, the $.ajax function has more flexibility. Just a personal preference.

jQuery AJAX Post Parameters

Here is the rundown on pass parameter:
type – HTTP Request Type. In this case ‘POST‘, but could be ‘GET‘ as well.
url – A string containing the URL to which the request is sent. Eg: HTTP://

data – A map or string that is sent to the server with the request.

success(data, textStatus, jqXHR) – A callback function that is executed if the request succeeds.

complete() – A callback function that is executed when everything is complete.

dataType – The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

jQuery Ajax Error Handling

The jQuery $.ajax function has a very robust error handling system. You can read more about it’s implementation in the jQuery Ajax Error Handling Function post.

jQuery Ajax Post Example

        url: "/form.php",
        type: "post",
        data: serializedData,
        // callback handler that will be called on success
        success: function(response, textStatus, jqXHR){
            // log a message to the console
            console.log("It worked!");
        // callback handler that will be called on completion
        // which means, either on success or error
        complete: function(){
            // enable the inputs

jQuery .Ajax Error Handling Function

Categories: AJAX, jQuery

jQuery Ajax Request – Background

The jQuery library provided easy access to AJAX requests with the following functions $.get, $.post, $.ajax:

  url: "test.html",
  context: document.body,
  success: function(){
    //do something on success

The jQuery ajax error function hook is part of the callback function queues. When the callback is invoked it receives the jqXHR, a string indicating the error type, and an exception object if applicable. There are several built in error strings provided by the exception option they include “abort“, “timeout“, “No Transport“, “parser error“. We also have access to server errors that are returned. In this implementation we want to catch the following.

  1. HTTP Status Code 404 Error – ajax file not found error
  2. HTTP Status Code 500 Error – ajax internal system error
  3. AJAX JSON Parse Errors
  4. jQuery AJAX Timeout Errors
  5. jQuery AJAX Abort Errors
  6. Browser/Connectivity Errors
  7. AJAX no transport error
  8. Other Unknown Errors

jQuery .ajaxSetup() Function

It is possible to set default values for all jQuery AJAX requests using the JQuery .ajaxSetup()function. The function is used to set default key/value pairs for all future AJAX requests. Looks like this:

     key: 'value'

jQuery Ajax Error Function

Let’s start building the function the will return the Ajax error. It will be a series of if else statements to text the chain of possible errors. We’ll test in a specific order and set an alert for each of the caught errors. We’ll also set the new function to the default error handling function with $.ajaxSetup().

Share the love!
$(function() {
		error: function(jqXHR, exception) {
			if (jqXHR.status === 0) {
				alert('Not connect.\n Verify Network.');
			} else if (jqXHR.status == 404) {
				alert('Requested page not found. [404]');
			} else if (jqXHR.status == 500) {
				alert('Internal Server Error [500].');
			} else if (exception === 'parsererror') {
				alert('Requested JSON parse failed.');
			} else if (exception === 'timeout') {
				alert('Time out error.');
			} else if (exception === 'abort') {
				alert('Ajax request aborted.');
			} else {
				alert('Uncaught Error.\n' + jqXHR.responseText);

Once the default error handling action is set, you can leverage it by calling the existing jQuery ajax functions.

Ajax Error handling Examples:

// jQuery AJAX Error Handler
  url: "test.php"

// jQuery AJAX Get Error Handler

// jQuery AJAX post Error Handler

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.stopPropagation();, '_blank');

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() {
           ("www.","")+"'])").each(function() {
       $(this).click(function(event) {
   , '_blank');
.externalLink {
    background: url("/images/externalLink.png") no-repeat scroll right center transparent;
    padding-right: 13px;
© 2014 - - Unseen Revolution LLC. 333 NW 4th Ave. Portland, OR 97209
By Portland, OR Category: Webinar Portland, OR Category: Webinar Portland, OR Category: Webinar