Video: Is Node.js Better?

Categories: javascript, Node.js

Brian Ford (@brixen ) gives a very interesting talk @ jsconf 2012 about the conversation of ‘which is better?’. He points out that humans really don’t do well at comparing things.

He looks at the support and excitement in the Node.JS community. How javascript has a large number of developers, but perhaps has some challenges in the future. Then looks at ruby on rails -vs- node.js.

About Brian Ford

Brian has been working on Rubinius since December 2006 and with Engine Yard since January 2008. He created the RubySpec project to improve the standards for high quality, consistent, and compliant Ruby implementations. He hopes to improve Ruby and thereby make the lives of developers even better. He enjoys whisk(e)y but will accept good wine in a pinch.


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_deregister_script('jquery');
      wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', false, '1.7.2');
      wp_enqueue_script('jquery');
      }
   }
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
http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

Microsoft’s jQuery CDN
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js

jQuery’s CDN
http://code.jquery.com/jquery-1.7.2.min.js

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 http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js


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!');
});
jQuery.noConflict();
(function($) { 
  $(function() {
   // by passing the $ you can code using the $ alias for jQuery
   alert('Page: ' + $('title').html() + ' dom loaded!');
  });
})(jQuery);

.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:

$.post({
  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.

$.ajax({
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://www.Yourdomain.com/YourAjaxScript.php

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

$.ajax({
        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
            $inputs.removeAttr("disabled");
        }
    });

Google Local SEO Lessons

Categories: Local, SEO

Getting Your Business on Google Maps

If you’re a local business and are looking to drive local customers to your business site, a great place to start is Google places and Google maps. According to a new study from Bizible there are a few easy things you can do to improve your SEO and move up in the Google local rankings.

Two Parts to a Local Search Query:

  • 1The search city – “Portland” when searching for “Portland pizza.”
  • 2The search category – “pizza” when searching for “Portland pizza.” We also generated a list of synonyms for the search category

Integrated Search Results Factors:

  • 1Having the primary category match a broader category of the search category was associated with a 1.42 improvement in rank. For example, primary category is set to “restaurant” and the search category was “pizza.”
  • 2Having the search category or a synonym in the business name was associated with a 0.64 improvement in rank.
  • 3Having the search category or a synonym in “at a glance” was associated with a 0.36 improvement in rank.
  • 4Having five or more Google reviews was associated with a 0.31 improvement in rank.(more than 5 does little to improve your rank)
  • 5Having photos (at least 1) was associated with a 0.25 improvement in rank.

The average ranking improvement for listing that implement these suggestions improved by about three positions. That is significant when you realize that on average there are only 5 integrated results listed for a search.

Pure Local Search Results Factors:

  • 1Having five or more Google reviews was associated with a 1.47 improvement in rank.
  • 2Having the search city in “at a glance” was associated with a 1.42 improvement in rank.
  • 3Having the search category or a synonym in in review content was associated with a 0.97 improvement in rank.
  • 4Having the search category or a synonym in the business description was associated with a 0.85 improvement in rank.
  • 5Having the search category or a synonym in “at a glance” was associated with a 0.85 improvement in rank.
  • 6Having the primary category match the search category was associated with a 0.79 improvement in rank.
  • 7Having the search category or a synonym in in the business name was associated with a 0.75 improvement in rank.
  • 8Having a secondary business category that was a broader category than the search category was associated with a 0.68 improvement in rank. i.e. secondary category is “restaurant” when searching for “Portland pizza.”
  • 9Having at least one photo was associated with a 0.66 improvement in rank.
  • 10Owner verified was associated with a 0.52 improvement in rank.

Listings using these factors on average saw a ranking improvement of 9 positions.

Search Engine Optimization Consulting

As you can see there are a few things to do to make a big difference in the SEO of your business listing. We at Unseen Revolution are search engine optimization specialists and can help you improve search engine ranking, list on Google Places for business, or list your business on Google maps.

The full report can be reviewed by visiting bizible.com


Solution: Firefox Font-Face Cross Domain Problem

Categories: Apache, CSS, Firefox, HTML

Firefox Font-Face Cross Domain Problem:

The other day I was working on a website that we were accelerating with a content deliver network (CDN). All the static content was to go through the cdn including the styles (css) file. We ran into a weird bug on Firefox. Font-face styles were not showing. The fonts were loading off the cdn.mysite.com sub domain while the rest of the site was running off mysite.com.

@font-face{
	font-family:'PreloSlab';
	src:url('../fonts/preloslab-medium-webfont.eot');
	src:url('../fonts/preloslab-medium-webfont.eot?#iefix') format('embedded-opentype'),
		url('../fonts/preloslab-medium-webfont.woff') format('woff'),
		url('../fonts/preloslab-medium-webfont.ttf') format('truetype'),
		url('../fonts/preloslab-medium-webfont.svg#PreloSlabMedium') format('svg');
	font-weight:normal;font-style:normal
	}

Reason:

Seems that Firefox supports the Cross-Origin Resource Sharing standard (CORS) for HTTP requests of some types of resource. This is a way for a remote host to control access to some types of resource. As it turns out, web fonts are subject to CORS. So, the appropriate Access Control headers need to be sent to the browser to allow the domain originating the request (the Origin) access to the resource.

Firefox Font-Face Cross Domain Solution:

Seems messy but it really isn’t. The correct header is:

Access-Control-Allow-Origin: http://mysite.com

On an Apache server you can accomplish this with a little edit to the .htaccess file.

<FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://mysite.com"
  </IfModule>
</FilesMatch>
Note: while you should be able to list several domains separated by a comma. This did not work. I had to use Header set Access-Control-Allow-Origin “*” for multiple domains.

Font-Face Mime Types

While you are at it, you can also add the correct mime types to the files.

AddType application/vnd.ms-fontobject .eot
AddType font/ttf .ttf
AddType font/otf .otf
AddType application/x-font-woff woff

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:

$.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:

$.ajaxSetup({
     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() {
	$.ajaxSetup({
		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
$.ajax({
  url: "test.php"
});

or
// jQuery AJAX Get Error Handler
$.get("test.php");

or
// jQuery AJAX post Error Handler
$.post("test.php");

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.

© 2014 - www.UnseenRevolution.com - Unseen Revolution LLC. 333 NW 4th Ave. Portland, OR 97209
5448c80b614dd
By
UnseenRevolution.com Portland, OR Category: Webinar
UnseenRevolution.com Portland, OR Category: Webinar
UnseenRevolution.com Portland, OR Category: Webinar