Check if a language file is loaded for jQuery Globalization plugin

Recently, I wrote my first jQuery Globalization plugin introductory post. I mentioned that I will write a tutorial for Globalization plugin and I am. While writing the tutorial I thought I’ll write one of my short Friday jQuery tips.

In this post you will learn how to check if a specific jQuery Globalization plugin language file is loaded or not. Globalization plugin saves localization data and all information in jQuery.cultures object. By default English language is added. So if you add "Inuktitut" language (code iu) the jQuery.cultures object will be extended and will have jQuery.cultures.iu object in it.

So to check if particular language file is loaded all we need to do is to check if jQuery.cultures.langCode is defined. Here is an example:

if($.cultures.iu){
    // Inuktitut jquery.glob.iu.js lang file is loaded
}else {
    // Inuktitut language is not loaded, load it here
}

Some cultures have different alphabet, so they will have that appended in their language and culture names. For example Inuktitut has Syllabics (iu-Cans) and Latin alphabets (iu-Latn), So you will not be able to check the file existence with the code above. Here is a syntax to do it:

if($.cultures.iu-Latin){
    // Will not work
}

// Better way to check if the lang file is loaded
if($.cultures["iu-Latn"]){
    // Inuktitut jquery.glob.iu-Latn.js lang file is loaded
}else {
    // Inuktitut language is not loaded, load it here
}

JavaScript to detect iPad visitors

This post gives you a short JavaScript function to detect your iPad users. Without any further ado, a javascript code to detect iPad users:

function isiPad(){
    return (navigator.platform.indexOf("iPad") != -1);
}

You can also detect browser version and some other stuff by parsing user agent string. Here is an iPad Safari’s user agent string for your reference:

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

Recently a friend of mine got himself an iPad and I couldn’t not notice how his internet browsing device preferences are changing (PC & iPad). More and more people are using hand held devices namely iPad to browse the internet. So it’s about time to show your iPad visitors some love and display your website designed specifically for iPad.

Let’s see how to do this. There are two way:

  1. Redirect iPad visitors
  2. Apply different CSS file for iPad users

Most of the posts on the internet related to iPad user detection are suggesting and showing you how to redirect (including myself in my previous iPhone & iPod detection post). However, I would recommend the second option, applying different CSS file.

You can apply the same technique described in applying different styling for javascript enabled browser with CSS post and apply different CSS rules for iPad visitors.

Sidenote: If you decide to redirect iPad users rather than apply different CSS style rules, than I would recommend using server side detection and redirection. You can see an example PHP code by David Walsh.

jQuery Globalization plugin — jquery.glob.js

This is the first post of a series that are dedicated to jQuery’s new Microsoft contributed Globalization plugin or shortly jquery.glob.js. In this first post I will try to cover the very basics like library licensing, “the good & the bad” and some thoughts on how it could be improved (IMO).

I will be post some jQuery globalization plugin tutorials in coming days, so bare with me.

Before we jump into licensing and support issues, first things are first. What’s up with the name? It’s confusing! When did we start calling localization (l10n) a globalization?! I haven’t seen any g12n abbreviations lately, have you? When I first came across it, I thought it was some wicked jQuery solution to "global variables are evil" idea or solution to some other problem that I am not even familiar with :) Don’t you agree, it’s confusing a bit.

So, there you go. One little improvement: "Don’t confuse, rename it!"

Before we talk about the jQuery globalization plugin license, let me mention that this plugin is now officially supported by jQuery Project. Which means that it will be under continues improvement by jQuery core team and will be compatible with the future jQuery and jQuery UI releases. Also globalization plugin will become a part of the jQuery UI project.

jQuery Project officially supports jQuery Globalization plugin.

Now, the legal stuff – the license. Because jQuery project accepted the globalization plugin as officially supported (and of course because Microsoft agreed to its terms) jQuery Globalization plugin is distributed under the same license as core jQuery.js. So you are safe to do pretty much anything.

jQuery Globalization plugin is licensed under the same non-restrictive terms as the core jQuery.js

After playing with the plugin for a while I realized that it does not do any DOM manipulations and you certainly don’t expect any animations. So what’s the point of having it as jQuery plugin and not a general JavaScript globalization/localization library? This way a larger community could benefit from it. I guess it was more of marketing decision rather than technical.

JavaScript library alternative to globalization plugin would be nice.

To be honest, JavaScript and jQuery community had a lack of localization libraries and jQuery Globalization plugin with over 350 localizations is a great solution. Surely, plugin’s exposed function names and namespacing could be improved, and most probably will be, but we’ll talk about it in our next “jQuery Globalization plugin tutorial” post. Stay tuned…

Russian CDN for jQuery

I recently discovered that the biggest Russian search engine Yandex (yeah, it’s bigger than Google in Russia) is using jQuery on its home page. It also hosts all previous jQuery versions on it’s fast gzip enabled servers just like Google and MIcrosoft do.

Because most of the Russian internet users have visited Yandex already, they already have it in their browser cache. I also did route tracing from Russian server to Google CDN servers and I was directed to the server in California, USA and pining the local Russian CDN server was at least 3 times faster.

Anyway, if you decide to use Russian CDN to host your jQuery files here are the links:

Minified versions
http://yandex.st/jquery/1.2.6/jquery.min.js
http://yandex.st/jquery/1.3.0/jquery.min.js
http://yandex.st/jquery/1.3.1/jquery.min.js
http://yandex.st/jquery/1.3.2/jquery.min.js
http://yandex.st/jquery/1.4.0/jquery.min.js
http://yandex.st/jquery/1.4.1/jquery.min.js
http://yandex.st/jquery/1.4.2/jquery.min.js

Non minified versions
http://yandex.st/jquery/1.2.6/jquery.js
http://yandex.st/jquery/1.3.0/jquery.js
http://yandex.st/jquery/1.3.1/jquery.js
http://yandex.st/jquery/1.3.2/jquery.js
http://yandex.st/jquery/1.4.0/jquery.js
http://yandex.st/jquery/1.4.1/jquery.js
http://yandex.st/jquery/1.4.2/jquery.js

jQuery UI links

http://yandex.st/jquery-ui/1.8.2/jquery-ui.min.js

Hosted versions
1.8.2, 1.8.1, 1.8.0, 1.7.3, 1.7.2, 1.7.1, 1.7.0, 1.6.0

jQuery UI modules can be downloaded seperately
http://yandex.st/jquery-ui/1.7.2/effects.blind.js
http://yandex.st/jquery-ui/1.8.0/jquery.effects.blind.min.js

Language files
http://yandex.st/jquery-ui/1.7.2/i18n/ui.datepicker-ru.js
http://yandex.st/jquery-ui/1.8.0/i18n/jquery.ui.datepicker-ru.min.js

jQuery UI CSS files (matches original directory names)
http://yandex.st/jquery-ui/1.8.0/themes/humanity/jquery.ui.all.min.css

iPhone / iPod detection using jQuery & JavaScript

In this post you will learn how to detect iPhone/iPod using javascript/jQuery, redirect your iPhone users to mobile version of your site using javascript and alternative and better way to redirect your visitors using server-side PHP code snippet.

The latest buzz around jQuery is upcoming jQuery mobile – support for mobile devices. Current jQuery core work fine on iPhone and iPod touch browsers and most of us have created a mobile version of our websites, developed or converted websites for others. Basically, jQuery is already being used on iPhone and iPod touch devices. Without any further ado…

Javascript code to detect iPhone and iPod browsers

// Return boolean TRUE/FALSE
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

You might wonder why do we even need to detect if our website is ran on iPhone Safari or normal desktop Safar if jQuery works fine on both. Well, there are Safari specific CSS features that you might want to utilize and you need to know if the current browser is Safari, then you may also want to consider reducing resource consuming features like animations for iPhone version of your site.

Redirecting iPhone & iPod users

You may also use this script to redirect iPhone and iPod users to your website’s mobile version:

// Redirect iPhone/iPod visitors
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}
if(isiPhone()){
    window.location = "mob.example.com";
}

For example: if your website is www.example.com and you have a mobile version at mob.example.com, then put the following script to your www.example.com.

Redirect iPhone users using PHP

It is better to detect and redirect your iPhone users on the server-side. Here is a PHP code to redirect iPhone users:

// Redirect iPhone/iPod visitors
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') ||
   strpos($_SERVER['HTTP_USER_AGENT'], 'iPod')){
      header("Location: http://mob.example.com");
}

User agent strings for your reference:

/*
User Agent String for iPhone
    Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko)
    Version/3.0 Mobile/1A543a Safari/419.3
    
User Agent String for iPod Touch
    Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko)
    Version/3.0 Mobile/3A101a Safari/419.3
*/

As final words, I would like to remind you that sometimes your visitors would not like to be redirected to mobile versions of your websites. That’s why your mobile version should always include a link to your non-mobile website. The above scripts can be rewrote to check if user has chosen not to be redirected. Either set cookie or a URL parameter.

jQuery mobile source code

If you want to download jQuery Mobile source code and look into it just like everybody else, we are all out of luck :(  As I mentioned in my previous post jQuery mobile facts, the source code will be available in October this year.

The jQuery Mobile source will not be in a separate jquery.mobile.js file. It will be right in the jQuery core. This means that jQuery team is fixing and improving jQuery core so that it works nicely in all major mobile phones and devices.

By the way, if you want to keep track of the jQuery mobile source code and be the first one to download it, when it is available, you should watch jQuery on GitHub.

The big part of the upcoming jQuery mobile is new UI components that work and render nicely in all mobile devices and degrade gracefully. So, keep an eye on jQuery UI as well. Here is the jQuery UI GitHub page.

Meanwhile you can read all jQuery mobile facts here.

jQuery & Cookies (get/set/delete & a plugin)

In this post I would like to share javascript functions that will help you easily get, set, delete and basically manage your cookies. Also, link to jQuery Cookie plugin, it’s improved version with more functions and of course easy to read and short examples on how to use these functions.

I will try to keep this post short and will not explain what cookies are and how to eat them. There are plenty of articles covering it already.

Here are javascript functions by Peter-Paul Koch to getCookie(), setCookie() and deleteCookie():

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}
/*
  Changed function names from readCookie(), createCookie()
  and eraseCookie() to getCookie(), setCookie() and
  deleteCookie().
*/

Here is an example that shows you how to use those functions in your javascript to create, edit and delete your cookies:

// Create/write a cookie and store it for 1 day
setCookie('myCookie', 'myValue', 1);

// Get my cookie
getCookie('myCookie');

// Delete/erase my cookie
deleteCookie('myCookie');

These 3 javascript functions are all you need to manage your cookies, but if you want to do it in “jQuery style” than you can use jQuery Cookie plugin or it’s improved version.

Here is how to use jQuery Cookie plugin in your code:

// Setting a cookie
$.cookie('myCookie':'myValue');

// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com', secure: true });

// Get a cookie
$.cookie('myCookie');

// Delete a cookie
$.cookie('myCookie', null);
With an improved version of the plugin you can set and get multiple cookies in one call. The improved version of the jQuery Cookie pluin only adds few additional bytes. So it really worth it. 
// Set multiple cookies
$.cookie({ 'cookie1':'value1', 'cookie2':'value2' });

jQuery Mobile

jQuery Mobile is an attempt to create a javascript framework that would work on all major mobile browsers. In this post I will try to lay down all the facts that I could find about jQuery Mobile, so that you are up to date.

jQuery team has mentioned that they were planning and started to work on jQuery for Mobile devices when they announced jQuery 1.4. John Resig said that they already had different mobile devices from sponsor for testing purposes. Anyway, jQuery Mobile is officially announced now, but there is a very little information about it.

Here are some facts that I found:

  1. jQuery Mobile will be in core, NOT as a separate distribution like jquery.mobile.js
  2. jQuery UI team will improve current jQuery UI and develop new mobile components (initial designs).
  3. Release of the jQuery Mobile and new jQuery UI components is planned for October 2010.
  4. As of writing of this post, jQuery Mobile source code is not available. The code will be pushed to the jQuery core’s GitHub repository and announced on the official jQuery mobile page.
  5. You can help jQuery Mobile project by testing jQuery core on your mobile devices at TestSwarm.

That’s all I could find on jQuery Mobile for now. Subscribe to my RSS or follow me on Twitter to stay updated about news related to jQuery Mobile.

jQuery.live() – event binding to AJAX loaded elements

jQuery.live() function was introduced in jQuery version 1.3. It makes it easy to dynamically bind events to DOM elements that have not yet been created. In other words, it helps you to easily attach events to AJAX loaded elements that match your criteria.

NOTE:
If for some reason you are using old versions of jQuery, prior to 1.3, you will need to use event delegation or another method as they are described in my previous post named “How to bind events to AJAX loaded elements in jQuery 1.2.x”.

So, how does .live() function works?

It uses event delegation technique to bind to the events that fire on your page. In other words, it binds an event to the DOM tree’s root and listens to all events. When an event is fired it checks it’s originator and checks if we have bound any events to that particular DOM element.

// Example usage of jQuery().live() function
$('.mySelector').live('click', function(event){
    // my click event handler
});

// As of jQuery 1.4.1 .live() can accept
// multiple events, just like .bind() does
$('input').live('focus blur', function(event){
    // fires on focus and blur
});

You can also pass in additional data to your events to overcome some issues caused by closure. This was introduced in jQuery 1.4. Also, it worth mentioning that data is passed when the binding is made. Keep this in mind when you pass in dynamic data.

$('.mySelector').live('click', {myVar: 'myVal'}, function(event){
    // my click event handler
});

NOTE:
Some events were not supported cross browser in jQuery 1.3. Events like submit were supported in Firefox only. This is resolved in jQuery 1.4. Other methods that were not supported cross browser in jQuery 1.3 include: focusin, focusout, mouseenter, mouseleave, etc.

NOTE:
.live() function also works with custom events.

jQuery.live() function performance

Because .live() uses event delegation and performs additional checks, it will always be slower then events attached to the DOM elements using .bind() function (this includes shorthands like: .click(), .submit(), etc.). However, you can improve your .live() function performance providing context (as of ver. 1.4).

// Using context for better performance
// Note that context is a DOM element, not jQuery
$('.mySelector', $('.myParent')[0]).live('click', function(event){
    // my faster click event
});

Unbinding events attached using .live() function

.unbind() function equivalent of .live() function is .die(). You can unbind ALL events attached using .live() function from an element by simply calling .die(). If you want to remove a specific event or a specific handler function of a specific event type, you can call .die('event', functionHandler).

// Remove ALL events attached using .live()
$('.mySelector').die();

// Remove myFunk() from click event
$('.mySelector').die('click', myFunk);

function myFunk(){
   alert("Clicked!");
}

If you have any questions or need any help, you can ask me on Facebook.

How to check loaded jQuery UI version?

In this post I will show how to check currently loaded jQuery UI version on the page. Unlike checking loaded jQuery version ( $().jquery ), checking jQuery UI version is a bit different.

Checking currently loaded jQuery UI version on the page:

// Returns jQuery UI version (ex: 1.8.2) or undefined
$.ui.version

// Alternatively
jQuery.ui.version

You would most probably use it in the if statement:

if($.ui && $.ui.version){
    // jQuery UI is loaded
}
You can also check if jQuery UI is loaded or not:
// Checking if jQuery UI is loaded or not
if($.ui){
    // jQuery UI is loaded
}else {
    // jQuery UI is not loaded
}

jQuery YouTube plugin demo

Long overdue demo for my jQuery YouTube plugin – jYouTube is now available here. The plugin can fetch and get you any YouTube video’s screenshot or thumbnail by its URL or video id.

Here is an example:

// Getting video screenshot by YouTube video ID
$.jYoutube('rSUfWXcNAOw');

// Returns video thumbnail by YouTube video URL
$.jYoutube('http://www.youtube.com/watch?v=rSUfWXcNAOw', 'small');

By default the plugin will return URL of the video screenshot (480×360). If you just need a video thumbnail (120×90) pass an optional second parameter "small".

See the plugin in action on jQuery YouTube demo page.

I hope you will find the plugin useful.

jQuery Twitter plugin update

A lot of users requested a demo for my jQuery Twitter plugin. It has been a while since I updated the plugin, so I downloaded the latest version and while looking thought the code found couple of bugs. So, here comes updated and fixed jQuery Tweeter plugin - jTwitter 1.1.1.

In this release, I fixed a little bug that would not allow you request Tweets without number of posts like this:

// Defaults to 5 latest posts
$.jTwitter('jQueryHowto', function(posts){
  //Callback function with the user data
});

You can specify the number of posts you want to be fetched like so:

// Get latest 13 posts
$.jTwitter('jQueryHowto', 13, function(posts){
  //Callback function with the user data
});

Also, I created a simple demo page for the plugin here. Please visit and see the code and also note that with this plugin you can create a custom Twitter badge with no design limitations!

Update: Pushed the project to GitHub.

jQuery code / syntax guidelines

We all write our own jQuery code and since creating custom jQuery plugins is so easy, we all create our own jQuery plugins. And all of us have our own code syntax preferences. For example:

function myFunction() {
    ...
}

// some prefere it like this
function myFunction()
{
    ...
}

If you want to publish your jQuery plugins following jQuery core code writing guidelines is a good idea. This would make your code more easier to read to other jQuery developers. Follow the link above and go through the guidelines (it will only take a few minutes). The guidelines page shows gives you general guidelines, but I went through the jQuery core code and found several additional ones. I lay they out at the end of this post.

In short, the official guidelines are as follows: (Taken from official docs)

  1. Use tabs to indent your code
  2. Use liberal spacing":
    function myFunction ( myVar, myVar2 ) {
        // Pay attention to spaces around
        // the brackets and curly brackets
    }
  3. Use strict equality checks whenever possible (===)
  4. Braces should always be used on blocks and statements should not be on the same line as a conditionals:
    // NO:
    if ( true ) blah();
    
    // YES:
    if ( true ) {
       blah();
    }
  5. When checking an object type:
    String: typeof object === "string"
    Number: typeof object === "number"
    Function: jQuery.isFunction(object)
    Array: jQuery.isArray(object)
    Element: object.nodeType
    
    See full list on official docs page (link above)
  6. Don't use "string".match() for RegExp, instead use .test() or .exec()
  7. Node related rules:
    • .nodeName should always be used in favor of .tagName.
    • .nodeType should be used to determine the classification of a node (not .nodeName).
    • Only attach data using .data().

Now let’s see other additional rules that I could spot reading the jQuery core code.

Additional jQuery code / syntax guidelines:

  1. The first thing that I noticed was multiline comments did not use common /* comment */ syntax. In jQuery core all multiline comments use line comment syntax // comment.
    // This is an example of multiline
    // comment syntax used in jQuery core.
  2. Local variables are declared and initialized on one line just below the function declaration with no extra line:
    function someFunction () {
        var target = arguments[0] || {}, i = 1, name;
    
        // Empty line and then the rest of the code
    }
  3. When declaring objects, there is no space between property name and colon:
    {
        myName: "",
        myFunc: function( ) {}
    }
  4. All strings are in double quotes " ", not single quotes ' ':
    var myMarkup = "<a href='/a'>a</a>";
  5. The last but not least, variable naming uses camelCase.

Dynamically create iframe with jQuery

This article explains and shows how to dynamically create an iframe in your HTML document’s DOM using jQuery and/or JavaScript. It also gives you an example code. This post is not extensive explanation of how to manage and work with iframes using jQuery. This post simply shows you how to dynamically create iframes using jQuery and JavaScript and serves as a note.

Creating iframe is similar to creating any DOM element. All you need to do is to use jQuery factory like this:

// Create an iframe element
$(‘<iframe />’);

// You can also create it with attributes set
$('<iframe id="myFrame" name="myFrame">');

// Finnaly attach it into the DOM
$('<iframe id="myFrame" name="myFrame">').appendTo('body');

Don’t forget that the iframe source is just an iframe’s attribute. So you can set that just like any other attribute.

// Setting iframe's source
$('<iframe />').attr('src', 'http://www.google.com'); 

UPDATE:

As BinaryKitten point’s out below, with jQuery 1.4 you can do it using the following syntax:

// Set attributes as a second parameter
$('<iframe />', {
    name: 'myFrame',
    id:   'myFrame',
    ...
}).appendTo('body');