jquery howto

73
FRIDAY, OCTOBER 15, 2010 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 } WEDNESDAY, OCTOBER 6, 2010 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) AppleWebKi t/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safar i/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. JQUERY HOWTO BLOG IS ABOUT JQUERY JAVASCRIPT LIBRARY. I COLLECT JAVASCRIPT CODE SNIPPETS, HOWTO'S, TIPS AND PERFORMANCE OBSERVATIONS. POSTED BY UZBEKJON AT 1:23 PM 0 COMMENTS LABELS: BEGINNER , JQUERY, PLUGIN, REFERENCE, TIP , TUTORIAL 20/01/2011 JQuery HowTo http://jquery-howto.blogspot.com/ 1/73

Upload: kzelda

Post on 02-Apr-2015

625 views

Category:

Documents


3 download

DESCRIPTION

JQuery HowTo

TRANSCRIPT

Page 1: JQuery HowTo

F R I D A Y , O C T O B E R 1 5 , 2 0 1 0

Check if a language file is loaded for jQueryGlobalization plugin

Recently, I wrote my first jQuery Globalization plugin introductory post. Imentioned that I will write a tutorial for Globalization plugin and I am. Whilewriting 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 pluginlanguage file is loaded or not. Globalization plugin saves localization data and allinformation in jQuery.cultures object. By default English language is added.So if you add "Inuktitut" language (code iu) the jQuery.cultures object will beextended 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 ifjQuery.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 theirlanguage and culture names. For example Inuktitut has Syllabics (iu-Cans) andLatin alphabets (iu-Latn), So you will not be able to check the file existencewith 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

}

W E D NE S D A Y, O C T O B E R 6 , 2 0 1 0

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 agentstring. 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) AppleWebKi

t/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safar

i/531.21.10

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

J Q U E R Y H O W T OB L O G I S A B O UT J Q UE R Y J A V A S C R I P T L I B R A R Y. I C O L L E C T J A V A S C R I P T C O D E S N I P P E T S , H O W T O ' S , T I P S A ND

P E R F O R M A N C E O B S E R V A T I O NS .

POSTED BY UZBEKJON AT 1: 23 PM 0 COM M ENTSLABELS: BEG INNER, JQ UERY, PLUGIN, REFERENCE, T IP , TUTO RIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 1/73

Page 2: JQuery HowTo

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

1. Redirect iPad visitors2. Apply different CSS file for iPad users

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

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

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

T U E S D A Y, O C T O B E R 5 , 2 0 1 0

jQuery Globalization plugin — jquery.glob.js

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

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

Before we jump into licensing and support issues, first things are first. What’sup with the name? It’s confusing! When did we start calling localization (l10n) aglobalization?! I haven’t seen any g12n abbreviations lately, have you? When Ifirst came across it, I thought it was some wicked jQuery solution to "globalvariables are evil" idea or solution to some other problem that I am not evenfamiliar 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 thatthis plugin is now officially supported by jQuery Project. Which means that itwill be under continues improvement by jQuery core team and will be compatiblewith the future jQuery and jQuery UI releases. Also globalization plugin willbecome a part of the jQuery UI project.

jQuery Project officially supports jQuery Globalization plugin.

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

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

After playing with the plugin for a while I realized that it does not do any DOMmanipulations and you certainly don’t expect any animations. So what’s thepoint of having it as jQuery plugin and not a general JavaScriptglobalization/localization library? This way a larger community could benefit fromit. 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 localizationlibraries and jQuery Globalization plugin with over 350 localizations is a greatsolution. Surely, plugin’s exposed function names and namespacing could beimproved, and most probably will be, but we’ll talk about it in our next “jQueryGlobalization plugin tutorial” post. Stay tuned…

S A T UR D A Y, S E P T E M B E R 2 5 , 2 0 1 0

POSTED BY UZBEKJON AT 1: 15 PM 0 COM M ENTSLABELS: CSS , HOW TO, JAV ASCRIPT, JQUERY, JQUERY M OB ILE, REFERENCE, T IP

POSTED BY UZBEKJON AT 3: 17 PM 0 COM M ENTSLABELS: INS IGHTS, JQ UER Y, JQUERY UI , NEW S, PLUG IN

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 2/73

Page 3: JQuery HowTo

Russian CDN for jQuery

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

Because most of the Russian internet users have visited Yandex already, theyalready have it in their browser cache. I also did route tracing from Russian serverto Google CDN servers and I was directed to the server in California, USA andpining 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 thelinks:

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

n.css

F R I D A Y , S E P T E M B E R 2 4 , 2 0 1 0

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 andalternative and better way to redirect your visitors using server-side PHP codesnippet.

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

POSTED BY UZBEKJON AT 10:19 AM 2 COM M ENTSLABELS: JQ UERY, LINK, PERFO RM ANCE, RESO URCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 3/73

Page 4: JQuery HowTo

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 iPhoneSafari or normal desktop Safar if jQuery works fine on both. Well, there are Safarispecific CSS features that you might want to utilize and you need to know if thecurrent browser is Safari, then you may also want to consider reducing resourceconsuming 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’smobile 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 versionat 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 aPHP 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/42

0+ (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 notlike to be redirected to mobile versions of your websites. That’s why your mobileversion should always include a link to your non-mobile website. The abovescripts can be rewrote to check if user has chosen not to be redirected. Eitherset cookie or a URL parameter.

Coupure de page insérée par AutoPager. Page ( 2 ).

POSTED BY UZBEKJON AT 10:36 AM 0 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, JQUERY, JQUERY M OB ILE, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 4/73

Page 5: JQuery HowTo

W E D NE S D A Y, S E P T E M B E R 2 2 , 2 0 1 0

jQuery mobile source code

If you want to download jQuery Mobile source code and look into it just likeeverybody else, we are all out of luck :( As I mentioned in my previous postjQuery 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 willbe right in the jQuery core. This means that jQuery team is fixing and improvingjQuery 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 bethe first one to download it, when it is available, you should watch jQuery onGitHub.

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

Meanwhile you can read all jQuery mobile facts here.

T U E S D A Y, S E P T E M B E R 2 1 , 2 0 1 0

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 Cookieplugin, it’s improved version with more functions and of course easy to read andshort examples on how to use these functions.

I will try to keep this post short and will not explain what cookies are and how toeat 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.len

gth,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 javascriptto create, edit and delete your cookies:

// Create/write a cookie and store it for 1 day

POSTED BY UZBEKJON AT 10:30 AM 0 COM M ENTSLABELS: INS IGHTS, JQ UER Y, JQUERY M O B ILE, JQUERY UI , NEW S

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 5/73

Page 6: JQuery HowTo

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 youwant to do it in “jQuery style” than you can use jQuery Cookie plugin or it’simproved 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 inone call. The improved version of the jQuery Cookie pluin only adds few additionalbytes. So it really worth it.

// Set multiple cookies

$.cookie({ 'cookie1':'value1', 'cookie2':'value2' });

S UN D A Y, A UG US T 2 9 , 2 0 1 0

jQuery Mobile

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

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

Here are some facts that I found:

1. jQuery Mobile will be in core, NOT as a separate distribution likejquery.mobile.js

2. jQuery UI team will improve current jQuery UI and develop new mobilecomponents (initial designs).

3. Release of the jQuery Mobile and new jQuery UI components is plannedfor 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 andannounced on the official jQuery mobile page.

5. You can help jQuery Mobile project by testing jQuery core on your mobiledevices at TestSwarm.

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

W E D NE S D A Y, A U G U S T 1 1 , 2 0 1 0

jQuery.live() – event binding to AJAX loaded

POSTED BY UZBEKJON AT 3: 04 PM 0 COM M ENTSLABELS: BEG INNER, JAV ASCRI PT, JQUERY, PLUG IN

POSTED BY UZBEKJON AT 9: 38 AM 0 COM M ENTSLABELS: JQ UERY M OB I LE, LINK, NEW S

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 6/73

Page 7: JQuery HowTo

elements

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

NOTE: If for some reason you are using old versions of jQuery, prior to 1.3, you will needto use event delegation or another method as they are described in my previouspost 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. Inother 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 anyevents 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 issuescaused by closure. This was introduced in jQuery 1.4. Also, it worth mentioningthat data is passed when the binding is made. Keep this in mind when you passin 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 likesubmit were supported in Firefox only. This is resolved in jQuery 1.4. Othermethods 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 willalways 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 unbindALL 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 aspecific event type, you can call .die('event', functionHandler).

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 7/73

Page 8: JQuery HowTo

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

M O ND A Y, J UL Y 1 2 , 2 0 1 0

How to check loaded jQuery UI version?

In this post I will show how to check currently loaded jQuery UI version on thepage. Unlike checking loaded jQuery version ( $().jquery ), checking jQuery UIversion 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.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

}

Coupure de page insérée par AutoPager. Page ( 3 ).

M O ND A Y, A P R I L 1 9 , 2 0 1 0

jQuery YouTube plugin demo

Long overdue demo for my jQuery YouTube plugin – jYouTube is now availablehere. The plugin can fetch and get you any YouTube video’s screenshot orthumbnail 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 youjust need a video thumbnail (120×90) pass an optional second parameter"small".

See the plugin in action on jQuery Y ouTube demo page.

POSTED BY UZBEKJON AT 10:33 AM 0 COM M ENTSLABELS: AJAX , BEGINNER, EV ENTS, JQUERY, PERFORM ANCE, REFERENCE

POSTED BY UZBEKJON AT 12:10 AM 2 COM M ENTSLABELS: BEG INNER, HOW TO, JQ UERY UI, T I P

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 8/73

Page 9: JQuery HowTo

I hope you will find the plugin useful.

S UN D A Y, F E B R U A R Y 2 8 , 2 0 1 0

jQuery Twitter plugin update

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

In this release, I fixed a little bug that would not allow you request Tweets withoutnumber 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 thecode and also note that with this plugin you can create a custom Twitter badgewith no design limitations!

Update: Pushed the project to GitHub.

T H UR S D A Y, F E B R UA R Y 1 8 , 2 0 1 0

jQuery code / syntax guidelines

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

function myFunction() {

...

}

// some prefere it like this

function myFunction()

{

...

}

If you want to publish your jQuery plugins following jQuery core code writingguidelines is a good idea. This would make your code more easier to read toother jQuery developers. Follow the link above and go through the guidelines (itwill only take a few minutes). The guidelines page shows gives you generalguidelines, but I went through the jQuery core code and found severaladditional 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 code2. Use liberal spacing":

function myFunction ( myVar, myVar2 ) {

// Pay attention to spaces around

// the brackets and curly brackets

}

POSTED BY UZBEKJON AT 5: 51 AM 1 COM M ENTSLABELS: JQ UERY, PLUGIN

POSTED BY UZBEKJON AT 6: 10 AM 0 COM M ENTSLABELS: JQ UERY, LINK, NEW S, PLUG IN

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 9/73

Page 10: JQuery HowTo

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 anode (not .nodeName).Only attach data using .data().

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

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 linecomment 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 thefunction 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 andcolon:

{

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.

S A T UR D A Y, F E B R UA R Y 1 3 , 2 0 1 0

Dynamically create iframe with jQuery

This article explains and shows how to dynamically create an iframe in yourHTML document’s DOM using jQuery and/or JavaScript. It also gives you anexample code. This post is not extensive explanation of how to manage and work

POSTED BY UZBEKJON AT 12:06 PM 2 COM M ENTSLABELS: BEG INNER, I NSI GHTS, JQUERY, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 10/73

Page 11: JQuery HowTo

with iframes using jQuery. This post simply shows you how to dynamicallycreate 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 touse 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 setthat 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 thefollowing syntax:

// Set attributes as a second parameter

$('<iframe />', {

name: 'myFrame',

id: 'myFrame',

...

}).appendTo('body');

T H UR S D A Y, J A NUA R Y 1 4 , 2 0 1 0

jQuery 1.4 Released

After a long break on the blog, I am back on the release date of jQuery version1.4! Today is jQuery’s birthday and what can be a better present than a newversion release? As I tweeted previously jQuery 1.4 has a lot to offer: betteriframe support, flexible events (this in particular), etc. If you have not beenkeeping up to date with jQuery 1.4 features John Resig will announce 1.4 releasedetails tomorrow.

Meanwhile, you can download it and see for yourself.

Download jQuery 1.4 1.4.2 from Google CDN (minified)Download jQuery 1.4 1.4.2 from Official jQuery website (minified)

Also, if you want to learn more about what is new in jQuery 1.4 then you mightfind the following resources useful:

1. 14 Days of jQuery2. Official jQuery Blog3. jQuery 1.4 Cheatsheet4. jQuery on Tweeter

If you have any more resources related to jQuery 1.4 please share in comments.

Happy Birthday jQuery and jQueriers :)

Coupure de page insérée par AutoPager. Page ( 4 ).

F R I D A Y , NO V E M B E R 6 , 2 0 0 9

Cross-domain RSS to JSON converter [jQueryplugin]

No doubt that Web2.0 is one of the best things that happened in our lifetime

POSTED BY UZBEKJON AT 10:19 AM 6 COM M ENTSLABELS: BEG INNER, DOM , HOW TO , HTM L, M ANIPULATIO N, REFERENCE

POSTED BY UZBEKJON AT 6: 49 AM 5 COM M ENTSLABELS: JQ UERY, LINK, NEW S, RESO URCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 11/73

Page 12: JQuery HowTo

(besides the internet itself). When we mention Web2.0 first things that come intoour minds are AJAX, rounded corners, clean and light layouts and of course RSSfeeds. Nowadays, you either provide an RSS feed or consume it in your web appusing AJAX/JavaScript.

The only bad thing is that you can not request cross-site content with AJAXrequests. Requesting someone else’s RSS in your JavaScript falls into thislimitations. One way to overcome this problem is to apply a server-side proxyworkaround. However, there is even better solution and workaround – RSS toJSON conversion.

Basically, using Google Feeds API service and jQuery plugin you can requestand get any RSS from different domain converted into the JSON object in yourjavascript.

Let’s see an example of RSS2JSON converter:

<script src="jquery.js"></script>

<script src="jquery.jgfeed.js"></script>

<script>

$.jGFeed('http://twitter.com/statuses/user_timeline/26767000.rss'

,

function(feeds){

// Check for errors

if(!feeds){

// there was an error

return false;

}

// do whatever you want with feeds here

for(var i=0; i<feeds.entries.length; i++){

var entry = feeds.entries[i];

// Entry title

entry.title;

}

}, 10);

</script>

In order to have universal client-side RSS to JSON converter you first need toinclude jquery.js and Google Feeds API plugin jquery.jgfeed.js. Then usejQuery plugin and Google Feeds API to get reliable and fast RSS to JSON(P)converter.

The code above gets Twitter RSS feeds in JSON format and does whatever itwants with it. Great workaround isn’t it :)

To see jGFeed()’s argument lists and how to use it please read this post.

T U E S D A Y, NO V E M B E R 3 , 2 0 0 9

Create callback functions for your jQuery plugins& extensions

Most of the time custom jQuery plugins and extensions that we create do notuse a callback functions. They usually simply work on DOM elements or dosome calculations. But there are cases when we need to define our owncustom callback functions for our plugins. And this is especially true whenour plugins utilize AJAX querying.

Let’s say our custom jQuery extension gets data by making some AJAX request.

$.extend({

myFunc : function(someArg){

var url = "http://site.com?q=" + someArg;

$.getJSON(url, function(data){

// our function definition hardcoded

});

}

});

POSTED BY UZBEKJON AT 8: 13 AM 9 COM M ENTSLABELS: AJAX , HO WTO , JQ UERY, JSO N, PLUGI N, T IP , TOO LS, W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 12/73

Page 13: JQuery HowTo

What is bad in this jQuery code is that the callback function is defined andhardcoded right in the plugin itself. The plugin is not really flexible and its userwill have to change the plugin code, which is bad!

So the solution is to define your own custom callback function argument. Here ishow it is done:

$.extend({

myFunc : function(someArg, callbackFnk){

var url = "http://site.com?q=" + someArg;

$.getJSON(url, function(data){

// now we are calling our own callback function

if(typeof callbackFnk == 'function'){

callbackFnk.call(this, data);

}

});

}

});

$.myFunc(args, function(){

// now my function is not hardcoded

// in the plugin itself

});

The above code shows you how to create a callback function for AJAX load, but ifyou want to create a simple callback function for your jQuery plugin, forexample the one that executes on your own custom events. To achive this youcan do the following:

$.extend({

myFunc : function(someArg, callbackFnk){

// do something here

var data = 'test';

// now call a callback function

if(typeof callbackFnk == 'function'){

callbackFnk.call(this, data);

}

}

});

$.myFunc(someArg, function(arg){

// now my function is not hardcoded

// in the plugin itself

// and arg = 'test'

});

S UN D A Y, NO V E M B E R 1 , 2 0 0 9

jQuery Twitter plugin update – jTwitter 1.1

Some time ago I created jQuery Twitter plugin – jTwitter. Plugin lets you get dataabout any Twitter user, such as user’s bio, profile image, homepage URL,background image URL, following count, followers count, messages count, etc.without any Twitter API key. It is very useful to attach additional Twitter data toyour site’s user profiles, etc.

However, it was not very handy for creating your own and custom Twitter Badge.Well, right until now! I updated jTwitter plugin and now it can get you not onlyTwitter user details but also any number of that user’s latest posts. And yes, allthese you can do without any Twitter API keys.

Here is the main function and its argument details:

$.jTwitter(username, numberOfPosts, callbackFunction);

/* username - Twitter username

POSTED BY UZBEKJON AT 7: 54 AM 5 COM M ENTSLABELS: AJAX , BEGINNER, EV ENTS, HO W TO, INSI GHTS, JQ UERY, PLUGIN, REFERENCE,TUTORI AL, W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 13/73

Page 14: JQuery HowTo

numberOfPosts - Number of user posts to get

callbackFunction - callback function to call

when data is loaded */

Let’s see a real life example now. In example below, we are fetching latest 3posts of jQueryHowto Twitter user and appending those post messages to someDOM element with an id=tweets.

$.jTwitter('jQueryHowto', 3, function(posts){

for(var i=0; i<posts.length; i++){

$('#tweets').append(posts[i].text);

}

});

Y ou can see example usage and demo here.

To get a clear view of what data is returned and available in your callback functionhere is an example of returned JSON data object:

/*

Example of returned object

*/

[

{

'in_reply_to_user_id':null,

'in_reply_to_screen_name':null,

'source':'web',

'created_at':'Fri Sep 18 06:11:15 +0000 2009',

'truncated':false,

'user':{

'profile_background_color':'9ae4e8',

'description':'jQuery and JavaScript howtos, tutorials, hac

ks, tips and performanace tests. Ask your jQuery questions here..

.',

'notifications':false,

'time_zone':'Central Time (US & Canada)',

'url':'http://jquery-howto.blogspot.com',

'screen_name':'jQueryHowto',

'following':true,

'profile_sidebar_fill_color':'e0ff92',

'created_at':'Thu Mar 26 14:58:19 +0000 2009',

'profile_sidebar_border_color':'87bc44',

'followers_count':2042,

'statuses_count':505,

'friends_count':1015,

'profile_text_color':'000000',

'protected':false,

'profile_background_image_url':'http://s.twimg.com/a/125320

9888/images/themes/theme1/bg.png',

'location':'',

'name':'jQuery HowTo',

'favourites_count':15,

'profile_link_color':'0000ff',

'id':26767000,

'verified':false,

'profile_background_tile':false,

'utc_offset':-21600,

'profile_image_url':'http://a3.twimg.com/profile_images/110

763033/jquery_normal.gif'

},

'in_reply_to_status_id':null,

'id':4073301536,

'favorited':false,

'text':'Host jQuery on Microsoft CDN servers http://retwt.me/

2N3P'

},

{

'in_reply_to_user_id':null,

'in_reply_to_screen_name':null,

'source':'<a href="http://www.hootsuite.com" rel="nofollow">H

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 14/73

Page 15: JQuery HowTo

ootSuite</a>',

'created_at':'Thu Sep 17 17:20:21 +0000 2009',

'truncated':false,

'user':{

'profile_sidebar_fill_color':'e0ff92',

'description':'jQuery and JavaScript howtos, tutorials, hac

ks, tips and performanace tests. Ask your jQuery questions here..

.',

'friends_count':1015,

'url':'http://jquery-howto.blogspot.com',

'screen_name':'jQueryHowto',

'following':false,

'profile_sidebar_border_color':'87bc44',

'favourites_count':15,

'created_at':'Thu Mar 26 14:58:19 +0000 2009',

'profile_text_color':'000000',

'profile_background_image_url':'http://s.twimg.com/a/125314

1863/images/themes/theme1/bg.png',

'profile_link_color':'0000ff',

'protected':false,

'verified':false,

'statuses_count':504,

'profile_background_tile':false,

'location':'',

'name':'jQuery HowTo',

'profile_background_color':'9ae4e8',

'id':26767000,

'notifications':false,

'time_zone':'Central Time (US & Canada)',

'utc_offset':-21600,

'followers_count':2038,

'profile_image_url':'http://a3.twimg.com/profile_images/110

763033/jquery_normal.gif'

},

'in_reply_to_status_id':null,

'id':4058535256,

'favorited':false,

'text':'jQuery Tip: Don't forget that you can load jQuery UI

files from Google servers as well http://bit.ly/fJs2r'

},

{

'in_reply_to_user_id':null,

'in_reply_to_screen_name':null,

'source':'web',

'created_at':'Thu Sep 17 05:44:30 +0000 2009',

'truncated':false,

'user':{

'profile_sidebar_fill_color':'e0ff92',

'description':'jQuery and JavaScript howtos, tutorials, hac

ks, tips and performanace tests. Ask your jQuery questions here..

.',

'friends_count':1015,

'url':'http://jquery-howto.blogspot.com',

'screen_name':'jQueryHowto',

'following':true,

'profile_sidebar_border_color':'87bc44',

'favourites_count':15,

'created_at':'Thu Mar 26 14:58:19 +0000 2009',

'profile_text_color':'000000',

'profile_background_image_url':'http://s.twimg.com/a/125304

8135/images/themes/theme1/bg.png',

'profile_link_color':'0000ff','protected':false,

'verified':false,

'statuses_count':503,

'profile_background_tile':false,

'location':'',

'name':'jQuery HowTo',

'profile_background_color':'9ae4e8',

'id':26767000,

'notifications':false,

'time_zone':'Central Time (US & Canada)',

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 15/73

Page 16: JQuery HowTo

'utc_offset':-21600,

'followers_count':2035,

'profile_image_url':'http://a3.twimg.com/profile_images/110

763033/jquery_normal.gif'

},

'in_reply_to_status_id':null,

'id':4048429737,

'favorited':false,

'text':'Added a demo page for my 'How to bind events to AJAX

loaded elements' blog post as requested by users http://bit.ly/q2

tWe'

}

]

As you can see, you get not only user’s latest posts but also all the informationabout posts and user who posted it on Twitter.

Y ou might also be interested in my jQuery Y ouTube Plugin. It gets any YouTube video’s thumbnail image.

If you are using Twitter don’t forget to follow me.

T U E S D A Y, O C T O B E R 2 0 , 2 0 0 9

JavaScript / jQuery password generator

This month, October, is a National Cyber Security Awareness Month. The aim isto increase cyber and internet security awareness among surfers. Google andothers are joining the move. So I thought I would write a post regarding internetsecurity to add my 2 cents. In this post you will find JavaScript function thatgenerates random passwords of any length as well as jQuery version.

JavaScript Password Generator

function password(length, special) {

var iteration = 0;

var password = "";

var randomNumber;

if(special == undefined){

var special = false;

}

while(iteration < length){

randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;

if(!special){

if ((randomNumber >=33) && (randomNumber <=47)) { continue;

}

if ((randomNumber >=58) && (randomNumber <=64)) { continue;

}

if ((randomNumber >=91) && (randomNumber <=96)) { continue;

}

if ((randomNumber >=123) && (randomNumber <=126)) { continu

e; }

}

iteration++;

password += String.fromCharCode(randomNumber);

}

return password;

}

This function takes two parameters: integer value for password length andoptional boolean value true if you want to include special characters in yourgenerated passwords.

Examples of generated passwords

password(8);

// Outputs: Yrc7TxX3

POSTED BY UZBEKJON AT 11:08 PM 9 COM M ENTSLABELS: AJAX , JQUERY, JSON, NEW S, PLUGIN, REFERENCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 16/73

Page 17: JQuery HowTo

password(12, true);

//Outputs: C}4_ege!P&#M

jQuery password generator

$.extend({

password: function (length, special) {

var iteration = 0;

var password = "";

var randomNumber;

if(special == undefined){

var special = false;

}

while(iteration < length){

randomNumber = (Math.floor((Math.random() * 100)) % 94) +

33;

if(!special){

if ((randomNumber >=33) && (randomNumber <=47)) { con

tinue; }

if ((randomNumber >=58) && (randomNumber <=64)) { con

tinue; }

if ((randomNumber >=91) && (randomNumber <=96)) { con

tinue; }

if ((randomNumber >=123) && (randomNumber <=126)) { c

ontinue; }

}

iteration++;

password += String.fromCharCode(randomNumber);

}

return password;

}

});

// How to use

$.password(8);

$.password(12, true);

T H UR S D A Y, S E P T E M B E R 1 7 , 2 0 0 9

Host jQuery on Microsoft CDN servers

After Microsoft decided to ship and use jQuery library for its JavaScript needs inVisual Studio, hosting jQuery on Microsoft CDN servers is actually a logical andgood decision. Yes, some of us might argue that Google already hosts jQuery,but Microsoft can not recommend to use its competitor’s services, can it?! :)

Anyway, intention of this post is not to discuss why Microsoft introduced its ownjQuery hosted servers, bu to share links to Microsoft hosted jQuery library. Herewe go:

jQuery 1.4.x

http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js

http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js

http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js

jQuery 1.3.2

http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js

http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min.js

http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2-vsdoc.js

http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js

Microsoft also host jQuery Validation and jQuery UI files.

Currently Microsoft AJAX CDN hosts only jQuery version 1.3.2, but they will addmore releases in the future. To see a full list of the JavaScript libraries and theirURLs that are already hosted on CDN cache go here: www.asp.net/ajax/cdn

POSTED BY UZBEKJON AT 6: 37 AM 2 COM M ENTSLABELS: JAV ASCRIPT, JQ UERY, SECURI TY, TOO LS

POSTED BY UZBEKJON AT 11:05 PM 2 COM M ENTSLABELS: AJAX , JAV ASCRIPT, JQUERY, LINK, NEW S, PERFORM ANCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 17/73

Page 18: JQuery HowTo

Coupure de page insérée par AutoPager. Page ( 5 ).

W E D NE S D A Y, S E P T E M B E R 1 6 , 2 0 0 9

Get URL parameters & values with jQuery

In this post, I would like to share a little jQuery code snippet that makes gettingURL parameters and their values more convenient.

Recently, while working on one of my projects, I needed to read and getparameter values from URL string of the current page that was constructed andsent by PHP script. I came across this short and sweet JavaScript code snippetby Roshambo that does just that.

// Read a page's GET URL variables and return them as an associat

ive array.

function getUrlVars()

{

var vars = [], hash;

var hashes = window.location.href.slice(window.location.href.

indexOf('?') + 1).split('&');

for(var i = 0; i < hashes.length; i++)

{

hash = hashes[i].split('=');

vars.push(hash[0]);

vars[hash[0]] = hash[1];

}

return vars;

}

The function returns an array/object with your URL parameters and their values.For example, consider we have the following URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

Calling getUrlVars() function would return you the following array:

{

"me" : "myValue",

"name2" : "SomeOtherValue"

}

To get a value of first parameter you would do this:

var first = getUrlVars()["me"];

// To get the second parameter

var second = getUrlVars()["name2"];

To make the script syntax to look more jQuery like syntax I rewrote it as anextension for jQuery:

$.extend({

getUrlVars: function(){

var vars = [], hash;

var hashes = window.location.href.slice(window.location.href.

indexOf('?') + 1).split('&');

for(var i = 0; i < hashes.length; i++)

{

hash = hashes[i].split('=');

vars.push(hash[0]);

vars[hash[0]] = hash[1];

}

return vars;

},

getUrlVar: function(name){

return $.getUrlVars()[name];

}

});

Now, if you include the above code in your javascript file, you can get URLparameter values in the following way:

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 18/73

Page 19: JQuery HowTo

// Get object of URL parameters

var allVars = $.getUrlVars();

// Getting URL var by its nam

var byName = $.getUrlVar('name');

That’s it! You might also find the following jQuery related articles on this blogsinteresting:

1. Cross-domain AJAX querying with jQuery2. Javascript for() loop vs jQuery .each() performance comparison3. Create jQuery custom selectors with parameters4. JavaScript / jQuery password generator

T U E S D A Y, A UG US T 1 1 , 2 0 0 9

QR Code (generator) plugin for jQuery &JavaScript

I recently came across a 2 dimensional barcode called QR Code. QR code’s arepopular in Japan and they are mainly used there to quickly get to some websiteon their mobiles by simply taking a picture of the QR code. You may read moreabout QR codes on Wikipedia.

Here is an example of QR code for jQuery HowTo blog:

If you have a QR code reader on your mobile take a picture of it and it will openthis website. Cool ha?!

Anyway, there are plenty of free online QR code generator sites, but noJavaScript and jQuery plugins/functions. So, I quickly searched for a free onlineQR code generator sites with “friendly” URL’s and put together a javascript andjQuery functions that generate QR barcode image’s URL for passed URLs. I usedKaywa & University of Bath services.

See jQuery and QR code in action on this demo page.

Here are javascript and jQuery QR code functions:

// JavaScript function

function qrcode(url, size){

if(typeof(size) == 'undefined') size = 8;

return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;

}

qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin

(function ($) {

$.fn.qrcode = function(url, size) {

if(typeof(size) == 'undefined') size = 8;

return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;

}

})(jQuery);

$().qrcode('http://www.google.com');

The code above utilizes Kaywa’s online QR code generator. You can specify

POSTED BY UZBEKJON AT 12:59 AM 13 CO M M ENTSLABELS: BEG INNER, HOW TO, HTM L, JAV ASCRIPT, JQ UERY, T IP , W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 19/73

Page 20: JQuery HowTo

image site as the second argument to the function. The size argument mut bebetween 1 and 40 and the generated image will 32 x your argument.

Here is javascript and jQuery code for University of Bath barcodegenerator:

// JavaScript function

function qrcode(url){

return 'http://go.bath.ac.uk/qr/download?DATA='+url;

}

qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin

(function ($) {

$.fn.qrcode = function(url) {

return 'http://go.bath.ac.uk/qr/download?DATA='+url;

}

})(jQuery);

$().qrcode('http://www.google.com');

NOTE: You can encode plain text messages. They are not limited to URLs...

T U E S D A Y, A UG US T 4 , 2 0 0 9

Can't set / change CSS background image withjQuery problem solution

Hello everyone. I’ve been busy lately with some projects and could not writemuch on “jQuery HowTo” blog. So, when I came across this little problem, Ithought I would share it with you.

Anyway, I was working on one of my projects and I needed to set a backgroundimage using jQuery on some div. At first my background setting code lookedlike this:

$('#myDiv').css('background-image', 'my_image.jpg');

// OR

$('#myDiv').css('background', 'path/to/image.jpg');

But to my surprise it didn’t do the trick. My div’s had no background images.FireBug showed no CSS background properties set and I could not see whybackground images were not being set by jQuery. Anyway, after 10-20 minutes Irealized that jQuery sets CSS properties as key : value and in our case valuedhad to be in url(image.jpg) form.

Solution to “background images are not being set” problem is to set them likethis:

$('#myDiv').css('background-image', 'url(my_image.jpg)');

// OR

$('#myDiv').css('background', 'url(path/to/image.jpg)');

T H UR S D A Y, J U L Y 2 , 2 0 0 9

jQuery.noConflict – Resolving conflicts with otherjavascript libraries that use $() function

One of the reasons that make a software popular is its extensions and plugins.jQuery has plenty of plugins that do almost anything you want, from simplebutton hide to full blown galleries. Plugins let non developers easily addfunctionality they need to their websites and there are times when one mightinclude more than one javascript library such as prototype.js, YUI or mootoolswith jQuery. They all use $ as their main function name. Including second librarymight brake the behavior of the first one. To resolve such cases jQueryintroduces .noConflict() method.

When you call .noConflict() jQuery will return $() to it’s previous owner and

POSTED BY UZBEKJON AT 2: 43 AM 5 COM M ENTSLABELS: JAV ASCRIPT, JQ UERY, PLUGIN, RESO URCE, TO OLS

POSTED BY UZBEKJON AT 12:36 AM 9 COM M ENTSLABELS: ATTRIBUTES, BEGI NNER, CSS , ERROR, JQUERY, T I P

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 20/73

Page 21: JQuery HowTo

you will need to use jQuery() instead of shorthand $() function.

.noConflict() usage example (From jQuery Docs site)

<html>

<head>

<script src="prototype.js"></script>

<script src="jquery.js"></script>

<script>

jQuery.noConflict();

// Use jQuery via jQuery(...)

jQuery(document).ready(function(){

jQuery("div").hide();

});

// Use Prototype with $(...), etc.

$('someid').hide();

</script>

</head>

<body></body>

</html>

You can also use the following code snippets to still use $() in your code, butwith one drawback, you will not have access to your other library’s $() method.

// Method 1

jQuery(document).ready(function($){

$("div").hide();

});

// Method 2

(function($) {

/* some code that uses $ */

})(jQuery);

TIP: Don’t forget that you can always assign jQuery to any other variable name to useit as your shorthand: var $_ = jQuery;

W E D NE S D A Y, J UL Y 1 , 2 0 0 9

Identifying & locating mouse position in jQuery

While writing the next jQuery tutorial I needed to identify and locate where themouse was on the page. Tracking mouse position on the page with jQuery iseasy. You don’t need to check what browser the script is running like it is usedto be with plain JavaScript. To identify where the mouse is in jQuery all you haveto do is to read event object’s .pageX and .pageY properties.

Example:

$().mousemove(function(e){

// e.pageX - gives you X position

// e.pageY - gives you Y position

});

The above jQuery code is binding a new ‘on mouse move’ event to the currentdocument and triggered every time mouse moves. The coordinates are calculatedin pixels from top left corner of the document. See the above code in action.

You may also want to know the coordinates of the mouse relative to some <div>or an element. Since jQuery returns mouse position relative to the documentroot, by subtracting element’s position from document root you get mousepositions relative to that element. Long story short here is the code to do justthat:

$("#someDiv").click(function(e){

var relativeX = e.pageX - this.offsetLeft;

var relativeY = e.pageY - this.offsetTop;

});

POSTED BY UZBEKJON AT 7: 42 AM 5 COM M ENTSLABELS: BEG INNER, HOW TO, INS IGHTS, JQ UERY, REFERENCE, T UTORIAL, W ORKAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 21/73

Page 22: JQuery HowTo

Don’t forget that you can bind any mouse event to any element and then getmouse positions. You can easily create a draggable object with click andmousemove events by simply setting the CSS top and left values to .pageX and.pageY.

Anyway, that’s how you locate and handle mouse positions in jQuery. Asalways, you don’t need to worry about cross browser compatibility issues whileusing jQuery. To learn more see more examples here.

Coupure de page insérée par AutoPager. Page ( 6 ).

W E D NE S D A Y, J UN E 2 4 , 2 0 0 9

jQuery custom selectors with parameters

My last tutorial on how to create a custom jQuery selector showed you thebasics of creating custom filters in jQuery. Now, it is time to get more seriouswith selectors and create more advanced jQuery selectors – custom jQueryselectors with parameters. To get an idea of what I am talking about think of:contains(someText) selector.

Anyway, let’s create our own jQuery selector that takes arguments. The basicsyntax is the same:

$.expr[':'].test = function(obj, index, meta, stack){

/* obj - is a current DOM element

index - the current loop index in stack

meta - meta data about your selector !!!

stack - stack of all elements to loop

Return true to include current element

Return false to explude current element

*/

};

meta is a parameter we are interested in. meta is an array that carries aninformation about our selector. Here is what it looks like:

$('a:test(argument)');

//meta would carry the following info:

[

':test(argument)', // full selector

'test', // only selector

'', // quotes used

'argument' // parameters

]

$('a:test("arg1, arg2")');

//meta would carry the following info:

[

':test('arg1, arg2')', // full selector

'test', // only selector

'"', // quotes used

'arg1, arg2' // parameters

]

Here as you can see, we can make use of the arrays fourth (meta[3]) value toget a hang of our parameters.

Creating custom jQuery selector with parameters

Now, let’s improve our selector from previous post that selects all links with nonempty rel attribute and make it select any element with specified non emptyattribute. Here is the code to do just that:

$.expr[':'].withAttr = function(obj, index, meta, stack){

return ($(obj).attr(meta[3]) != '');

};

POSTED BY UZBEKJON AT 11:20 PM 4 COM M ENTSLABELS: ATTRIBUTES, BEGI NNER, EV ENTS, HO W TO, JQ UER Y, REFERENCE, T UTORIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 22/73

Page 23: JQuery HowTo

See it in action here.

T H UR S D A Y, J U NE 1 1 , 2 0 0 9

Find & select all external links with jQuery

Selecting all external links and amending them in some way is probably one ofthe most used jQuery tutorials. By selecting all anchor links on the page and forexample adding a CSS class with only one jQuery line shows how jQuery issimple and powerful. Also if you are progressively enhancing your website this isone of the trick you might use.

Actually, I had to select all external links and add an image that indicates it theother day. So, I created a custom jQuery selector called :external that makesfinding external links easier for you. (Read “Custom jQuery Selectors” post tolearn how to create your own custom selectors)

External links custom jQuery selector code:

// Creating custom :external selector

$.expr[':'].external = function(obj){

return !obj.href.match(/^mailto\:/)

&& (obj.hostname != location.hostname);

};

// Add 'external' CSS class to all external links

$('a:external').addClass('external');

You can see this code in action here.

You may use the code above to:

Add CSS class to all external linksDynamically add an image after the link to indicate that it is an externallinkBind a click event to track what links where clickedetc.

Update: The return part was update to take into the account the mailto links assuggested in comments by Phillipp and Karl below.

W E D NE S D A Y, J UN E 1 0 , 2 0 0 9

Custom jQuery selectors

jQuery makes it easy to select elements you need using CSS selectors. It isundoubtedly one of the jQuery features that makes it a great javascript library.On top of standard CSS selectors jQuery introduces some custom selectorsthat makes your code even more simpler and easier to read.

Examples of custom jQuery selectors are: :header, :even, :odd, :animated,:contains(text), etc.

And the best part is that jQuery lets you create and define your own customselectors using custom selector creation template below.

jQuery Custom Selector Creation Template:

$.expr[':'].test = function(obj, index, meta, stack){

// obj - is a current DOM element

// index - the current loop index in stack

// meta - meta data about your selector

// stack - stack of all elements to loop

// Return true to include current element

// Return false to explude current element

};

// Usage:

POSTED BY UZBEKJON AT 6: 42 AM 3 COM M ENTSLABELS: HOW TO, INS IGHT S, JQUERY, REFERENCE, SELECTORS, T IP , TUT ORIAL

POSTED BY UZBEKJON AT 1: 57 AM 5 COM M ENTSLABELS: HOW TO, JQUERY, PLUGI N, REFERENCE, SELECTORS, T IP , T UTORIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 23/73

Page 24: JQuery HowTo

$('.someClasses:test').doSomething();

Let’s now create a very simple custom selector using the template above. Let’ssay we want a custom jQuery selector that will return elements with nonemptyrel attribute.

$.expr[':'].withRel = function(obj){

var $this = $(obj);

return ($this.attr('rel') != '');

};

// Usage:

$('a:withRel').css('background-color', 'yellow');

The code above creates a custom selector that will select only elements with notempty rel attributes. Here is the above code’s demo page.

You might also be interested in reading about jQuery custom functions.

UPDATE: Read about creating custom jQuery selectors with parameters.

S A T UR D A Y, J U NE 6 , 2 0 0 9

Mozilla Jetpack & jQuery

Jetpack is a new product of Mozilla Labs. It is basically a new way to createFirefox plugins using web programming languages like HTML, CSS andJavaScript. The idea behind is the same as for Adobe AIR. If you know HTML,CSS and JavaScript you can build a Firefox plugin in no time.

The bad news is that Jetpack is still in early developer testing stage, so it is notavailable in Firefox yet. The good news is that Jetpack is using jQuery and youcan use it to do all kinds of stuff like responding to user click events, manipulateany website DOM elements and use cross-site XMLHttpRequest object, etc.Besides, Jetpack can be setted up to use other javascript libraries such asprototype.js, dojo.js etc. and third party API libraries such as Twitter, Google,etc. API libraries.

Where to go from here?

If you want to learn more about Jetpack and how to use jQuery with it refer to thislinks:

1. Watch this Jetpack video Good starting point to get an idea of what Jetpack is and how jQuery isused within it. Also good starting point to understand what kind of thingscan be don with Jetpack.

2. Read Jetpack tutorial Official Jetpack introduction tutorial from Jetpack team. Probably the firstarticle you must read about developing for Jetpack.

3. Jetpack API documentation A list of global variables that are available in your Jetpacks. Currently ithas a very limited global variables and functions.

4. Jetpack plugin for your Firefox If you want to develop Jetpacks you need to install this Firefox plugin.

5. Available Jetpack to investigate the code here and here. Most developers prefer understanding the logic and learning byinvestigating someone else’s code easier.

I am planning to post more Jetpack tutorials on this blog and try to show whatkind of things can be done using Jetpack and jQuery. Keep tuned by followingme on Twitter (@jQueryHowto) or subscribe to blog’s RSS.

T H UR S D A Y, J U NE 4 , 2 0 0 9

jQuery Beginner tutorials

This post is about a decision I made yesterday to post more jQuery beginner

POSTED BY UZBEKJON AT 3: 43 AM 13 COM M ENTSLABELS: HOW TO, INS IGHT S, JQUERY, PLUGIN, REFERENCE, TUTORIAL

POSTED BY UZBEKJON AT 4: 04 AM 1 COM M ENTSLABELS: INS IGHTS, JQ UER Y, LINK, NEW S, PLUG IN, REFERENCE, RESOURCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 24/73

Page 25: JQuery HowTo

tutorials on the blog.

See a list of all jQuery beginner tutorials on this blog.

There were two reasons for me making this decision:

1. People are finding this jQuery blog searching for jQuery basics Analyzing my Google Analytics account I found that a lot of developerswho are landing on this blog through search are jQuery Beginners andlooking for basic jQuery method explanations. So publishing morebeginner tutorials would benefit them. They would get more relevantinformation from the new Beginner category posts.

2. I am being asked more and more jQuery Beginner questions I have been quite active on Twitter (@jQueryHowto) and other onlinediscussion boards lately answering and helping developers with theirjQuery problems. The jQuery community on twitter is quite active andmost of the jQuery problems I came across were jQuery beginnersquestions. I could not squeeze my ideas or explanations of jQuery basicsin 140 characters, so I had to search the web for explanation and post alink to the website.

Message to non beginner readers:

I hope I will not lose intermediate and advanced jQuery developers with thisposts. I enjoy your insights and comments on my posts and actually learn a lotmore from your feedback. I will try to post no more than one beginner tutorial orinsight per my regular post. I hope for your understanding.

List of jQuery Beginner Tutorials and posts:

I actually posted several jQuery Beginner tutorials and method explanations onthis blog with backdate. I will try to keep this post updated with the links for mybeginner posts so you can bookmark this page or share it with your jQuerybeginner colleagues.

See all jQuery beginner tutorials on this blog.

1. Using $.noConflict()2. How to check if checkbox is checked3. Identify how many elements were selected4. Adding custom functions to jQuery5. Identifying & locating mouse position in jQuery6. How to load jQuery from Google CDN servers7. Setting HTML tag’s attribute in jQuery8. Getting HTML tag’s attribute in jQuery9. Binding jQuery events to AJAX loaded elements

10. How to disable and enable an element11. Quick tip to solve a problem with setting CSS background image to an

element

Coupure de page insérée par AutoPager. Page ( 7 ).

T U E S D A Y, J UNE 2 , 2 0 0 9

Javascript for() loop vs jQuery .each()performance comparison

This post is an outcome of 15 minutes of free time and a question that I hadyesterday. This question were:

1. How fast jQuery’s .each() method is?2. How does it compare to javascript’s native for loop?

It is clear without any performance tests that native javascript for loop is faster,but I always used jQuery’s .each() utility with caution. It always felt like I willget a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers.Basically, I created an array and iterated through it using native for loop and

POSTED BY UZBEKJON AT 6: 38 AM 1 COM M ENTSLABELS: BEG INNER, NEW S, TUTORIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 25/73

Page 26: JQuery HowTo

jQuery’s .each() iterator. All I did was just an iteration and no arrayamendments or any other logic. I know it is very basic, but that’s exactly what Iwant to know. How fast they iterate!

Performance test code:

console.time('TestNative');

length = myArray.length;

for( i=0; i < length; i++){

myArray[i];

}

console.timeEnd('TestNative');

console.time('TestjQuery');

jQuery.each(myArray, function(i, val) {

val;

});

console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size Time

========== ======

10,000 7ms

100,000 62ms

1,000,000 613ms

jQuery .each() loop

Array size Time

========== ======

10,000 10ms

100,000 177ms

1,000,000 1100ms

As you can see native for loop is never over 1ms. That’s probably because weare not doing anything with our array and browser simply optimizes the code ormaybe its that fast :)

Usually we don’t have more than 1000 items in our arrays and objects, that iswhy I guess it can be concluded that using .each() loop in our code willnot cause any performance penalties.

F R I D A Y , M A Y 2 9 , 2 0 0 9

Tip for jQuery & handheld device developers

This week’s usual “Friday short post” about using jQuery in handhelddevices. If you are a developer who is using jQuery in applications that weredeveloped for use in environments with small processing power such as handhelddevices, mobile phones, PDA’s, etc. you will find this post useful.

Anyway, back to the topic. For whatever reasons you chose to use jQuery inyour application (I would suggest using plain javascript for better performance)jQuery effects such as animation, hide and show, etc. most likely were probablyone of the reasons. Unfortunately, jQuery effects are process intensive and in“slow” environments it is recommended to turn them off. Fortunately, jQueryprovides you with such a method. It lets you disable all animations and effects bychanging jQuery.fx.off setting to true.

// Dissable all effects

jQuery.fx.off = true;

// Shorthand

$.fx.off = true;

POSTED BY UZBEKJON AT 7: 08 AM 10 COM M ENTSLABELS: INS IGHTS, JAV ASCRIPT, JQ UERY, PERFO RM ANCE, REFERENCE, TEST, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 26/73

Page 27: JQuery HowTo

Now all your effects such as fadeIn(), fadeOut(), slideDown(), slideUp(),etc. will not be animated. They will simply be hidden and shown immediately (bychanging CSS rules display:none; display:block;) to save CPU processingtime.

NOTE: By setting the jQuery.fx.off back to false you enable all animations andeffects.

W E D NE S D A Y, M A Y 2 7 , 2 0 0 9

Google Feeds API - jQuery plugin

This jQuery plugin utilizes Google’s Feeds API and builds an abstraction layerthat makes Google feed API easier to use for jQuery developers. Theadvantage of using this lightweight jQuery plugin is that you don’t have to learnand go through new API documentation.

Download Google Feed API jQuery plugin – jGFeed.

Here is how to use the plugin:

$.jGFeed('http://feeds.feedburner.com/jQueryHowto',

function(feeds){

// Check for errors

if(!feeds){

// there was an error

return false;

}

// do whatever you want with feeds here

for(var i=0; i<feeds.entries.length; i++){

var entry = feeds.entries[i];

// Entry title

entry.title;

}

}, 10);

Available plugin arguments list:

jQuery Google Feed API plugin lets you specify the following settings:

url – URL of the feed that you want to loadcallback – callback function to call after RSS feed is loadednum (optional) – number of blog entries to load (defaults to 3)key (optional) – Google API key to use while loading RSS feeds.

The plugin returns false if there was an error while AJAX loading your feed or thefollowing feed object on success:

{

"title":"Blog Title",

"link":"http://www.example.com",

"author":"Author Name",

"description":"Blog description.",

"type":"RSS type (atom10, etc.)",

"entries":[

{

"title":"Blog entry title 1",

"link":"http://www.example.com/entry-1.html",

"author":"Post Author Name",

"publishedDate":"Mon, 25 May 2009 07:07:00 -0700",

"contentSnippet":"Short blog post snippet ...",

"content":"Longer snippet of the blog post",

"categories":[

"category 1",

"category 2",

"category 3"

]

POSTED BY UZBEKJON AT 6: 48 AM 3 COM M ENTSLABELS: ANIM ATION, HOW TO, INS IG HTS, JQUERY, PERFORM ANCE, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 27/73

Page 28: JQuery HowTo

},

{

"title":"Blog entry title 2",

"link":"http://www.example.com/entry-2.html",

"author":"Post Author Name",

"publishedDate":"Mon, 25 May 2009 07:07:00 -0700",

"contentSnippet":"Short blog post snippet ...",

"content":"Longer snippet of the blog post",

"categories":[

"category 3",

"category 2",

"category 1"

]

},

...

}

If you don’t specify a URL it will also return false. If you want to use your ownGoogle Feed API key you can get one here.

M O ND A Y, M A Y 2 5 , 2 0 0 9

diggthis.js + jQuery .wrap() is not working,causing Firefox to freeze and Safari to crush

I came across a forum post where user was experiencing problems while usingDigg this (diggthis.js) button code with jQuery’s .wrap() method. According tohim Mozilla Firefox (FF) is freezing and Apple Safari is crushing when he tries towrap the div that contains diggthis.js file with another new div like so:

<div class="rounded">

<script type="text/javascript">

digg_url = "myURL.com";

</script>

<script src="http://digg.com/tools/diggthis.js" type="text/java

script"></script>

</div>

And the jQuery code is:

$(document).ready(function(){

$("div.rounded").wrap('<div></div>');

});

This code seems to crush those browsers. Another way to do this is to removethe div that contains the script (.rounded), then create a new <div> and theninsert the removed div (.rounded) back into the newly created div like this:

$(document).ready(function(){

$("div.rounded").remove().wrap('<div></div>').appendTo("#some

where");

});

F R I D A Y , M A Y 2 2 , 2 0 0 9

Remove n’th table column - jQuery plugin

My usual short Friday post. Today I would like to share with you a new utility Iwrote to work with HTML tables. We already have jQuery functions to add tablerow, remove table row (on user click), add table row number plugin and now hereis jQuery code to remove table column.

jQuery utility to remove table’s n’th column:

$.fn.removeCol = function(col){

// Make sure col has value

POSTED BY UZBEKJON AT 9: 45 AM 9 COM M ENTSLABELS: AJAX , JQUERY, JSON, PLUGIN

POSTED BY UZBEKJON AT 7: 07 AM 0 COM M ENTSLABELS: DOM , ERROR, JQUERY, M ANIPULATIO N, T I P , W OR KAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 28/73

Page 29: JQuery HowTo

if(!col){ col = 1; }

$('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this)

.remove();

return this;

};

Just add this code to your javascript file and use it in your jQuery code like this:

// Remove all table's second columns

$('table').removeCol(2);

// Remove table's first column (default)

$('table').removeCol();

The function takes column number to delete as an argument and removes thatcolumn. If you don’t supply any column number it removes the first table columnby default.

Coupure de page insérée par AutoPager. Page ( 8 ).

T H UR S D A Y, M A Y 2 1 , 2 0 0 9

Remove table row on user click

This post is about removing a table row on user click. I needed this functionalityfor a project of mine. Online application had a table with data that user candynamically add and remove. With progressive enhancement I also need to add afunctionality to one of the tables that enables users to delete table rows whenthat table row is clicked.

jQuery code to delete clicked table row came out to be surprisingly short,only 3 lines of code.

// Select all table cells to bind a click event

$('table td').click(function(){

$(this).parent().remove();

});

Here, we are first selecting all table cells to bind our click event. On user click toany table cell click event fires. In the click event we are removing <td>’s parent,which is <tr>, thus removing whole row.

By popular user demand I’m including an example that lets deleting a tablerow on delete image click. Here is our HTML table:

<table>

<tr>

<td>row 1, cell 1</td>

<td><img class="delete" src="del.gif" /></td>

</tr>

<tr>

<td>row 2, cell 1</td>

<td><img class="delete" src="del.gif" /></td>

</tr>

</table>

Here is jQuery code to delete a row on delete image click:

$('table td img.delete').click(function(){

$(this).parent().parent().remove();

});

See demos here.

Bonus: Also delete a table row from database

The code above is enough if you don’t need to also delete a record from yourdatabase table. In my case I had to set up a server side code to do that. Withone extra AJAX call to my server side script the functionality was ready.

POSTED BY UZBEKJON AT 6: 01 AM 7 COM M ENTSLABELS: HOW TO, HTM L, JQUERY, M ANIPULATIO N, PLUGI N, REFERENCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 29/73

Page 30: JQuery HowTo

$('table td').click(function(){

$.get('deleteRow.php', {id: $(this).parent().attr('id')},

function(){

$(this).parent().remove();

});

});

In the jQuery code above, instead of removing table row straight away we aremaking an AJAX call to our server side code that also removes that row from ourdatabase and then on AJAX call completion we removing table row.

F R I D A Y , M A Y 1 5 , 2 0 0 9

jYouTube - jQuery YouTube Thumbnail plugin.Gets any YouTube video’s image/thumbnail

Writing short scripts and jQuery tips on Fridays became some kind of habit. Sothis Friday I will give you a small jQuery utility function that will give you a way toget any YouTube video’s still image or in other words any YouTube video’sthumbnail. All you need to know is that YouTube video’s URL address or at leastvideo’s YouTube ID.

Couple of months ago I wrote a javascript function that does just that, getsYouTube video’s thumbnail. Today, I am rewriting that code as a jQuery utilityfunction and releasing it as jQuery plugin called jYouTube.

Download jQuery Y outube plugin - jY ouTube

It takes any YouTube video URL or video ID as first parameter and thumbnail size(big or small) as the second parameter. Utility returns that video’s screenshotURL.

Here is how you use jYouTube plugin in your own code:

// Returns big screenshot by video id

$.jYoutube('rSUfWXcNAOw');

// Returns small thumbnail by YouTube video URL

$.jYoutube('http://www.youtube.com/watch?v=rSUfWXcNAOw', 'small')

;

See the plugin in action on jQuery Y ouTube demo page.

So here is the final jQuery YouTube plugin code for those who are interested:

$.extend({

jYoutube: function( url, size ){

if(url === null){ return ""; }

size = (size === null) ? "big" : size;

var vid;

var results;

results = url.match("[\\?&]v=([^&#]*)");

vid = ( results === null ) ? url : results[1];

if(size == "small"){

return "http://img.youtube.com/vi/"+vid+"/2.jpg";

}else {

return "http://img.youtube.com/vi/"+vid+"/0.jpg";

}

}

});

Y ou might also be interested in jQuery Twitter plugin. Gets any Twitter user information and tweets (does not require API key).

POSTED BY UZBEKJON AT 12:35 AM 3 COM M ENTSLABELS: HOW TO, HTM L, JQUERY, M ANIPULATIO N

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 30/73

Page 31: JQuery HowTo

T U E S D A Y, M A Y 1 2 , 2 0 0 9

Replacing images at time intervals

This post is somehow a continuation of our previous post on replacing images,but this post is one step closer to creating an image gallery using jQuery. In thispost I will show you how to replace one image with another one in specific timeintervals. For example: replacing image1.jpg with image2.jpg every 5 seconds.

In javascript, whenever one says “every X seconds” or “time intervals” s/he istalking about javascript’s setInterval() function and this post is no exception.

So, before we continue, we need to define where our images are coming from.Images URLs can be stored in javascript array or we could choose more elegantway and simply read them from HTML document.

Imagine we have this HTML markup:

<div id="myGallery">

<img src="image1.jpg" class="active" />

<img src="image2.jpg" />

<img src="image3.jpg" />

</div>

We need to hide all images but class="active" one and overlay all of them onone another. Here is a CSS to do that:

#myGallery{

position:relative;

width:400px; /* Set your image width */

height:300px; /* Set your image height */

}

#myGallery img{

display:none;

position:absolute;

top:0;

left:0;

}

#myGallery img.active{

display:block;

}

Now, lets write jQuery function that will fade out currently active image and fadein the next image. Here is jQuery code:

function swapImages(){

var $active = $('#myGallery .active');

var $next = ($('#myGallery .active').next().length > 0) ? $('#m

yGallery .active').next() : $('#myGallery img:first');

$active.fadeOut(function(){

$active.removeClass('active');

$next.fadeIn().addClass('active');

});

}

And now all that’s left is to add setInterval() with our function and the time intervalwe want our image to fade out and fade in.

// Run our swapImages() function every 5secs

setInterval('swapImages()', 5000);

Now we have gallery/slideshow with images changing every 5 seconds. You caneasily customize this jQuery script to create your own slideshow.

Here is how your final code should look like:

<html>

<head>

<script src="jquery.js">

</script>

POSTED BY UZBEKJON AT 8: 43 AM 1 COM M ENTSLABELS: HOW TO, JQUERY, PLUGI N, TO OLS

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 31/73

Page 32: JQuery HowTo

<script>

function swapImages(){

var $active = $('#myGallery .active');

var $next = ($('#myGallery .active').next().length > 0) ? $

('#myGallery .active').next() : $('#myGallery img:first');

$active.fadeOut(function(){

$active.removeClass('active');

$next.fadeIn().addClass('active');

});

}

$(document).ready(function(){

// Run our swapImages() function every 5secs

setInterval('swapImages()', 5000);

}

</script>

<style>

#myGallery{

position:relative;

width:400px; /* Set your image width */

height:300px; /* Set your image height */

}

#myGallery img{

display:none;

position:absolute;

top:0;

left:0;

}

#myGallery img.active{

display:block;

}

</style>

</head>

<body>

<div id="myGallery">

<img src="image1.jpg" class="active" />

<img src="image2.jpg" />

<img src="image3.jpg" />

</div>

</body>

</html>

The code above is simplified.

T H UR S D A Y, M A Y 7 , 2 0 0 9

Disable submit button on form submit

Form submission is one of the most used actions and double form submission isone of most occurred problems in web development. Rather than dealing with thisproblem server side, eating up your CPU process time, it is much easier andbetter to deal with this problem client side using JavaScript. When we talkjavascript, what it a better way to write it other than using jQuery?!

So this Friday’s quick tip is disabling form submit button on its click orpreventing double form submission by disabling submit button.

Consider we have this HTML form in our code:

<form id="myform" action="someUrl.php" method="get">

<input name="username" />

<!-- some more form fields -->

<input id="submit" type="submit" />

</form>

Here is a jQuery code that disables submit button on form submission:

$('#myform').submit(function(){

$('input[type=submit]', this).attr('disabled', 'disabled');

});

POSTED BY UZBEKJON AT 4: 42 AM 12 COM M ENTSLABELS: ANIM ATION, CSS, HOW TO , HTM L, JQUERY, TUTORIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 32/73

Page 33: JQuery HowTo

The above jQuery code binds a submit event to our #myform form, then finds itssubmit button and disables it.

Bonus: disable submit button on form submission for allforms on your page.

// Find ALL <form> tags on your page

$('form').submit(function(){

// On submit disable its submit button

$('input[type=submit]', this).attr('disabled', 'disabled');

});

Want to disable any other elements using jQuery? Read my previous “Disablingand enabling elements in jQuery” (very short) post.

F R I D A Y , M A Y 1 , 2 0 0 9

Remove the bottom table row using jQuery

I have posted a small jQuery code a while ago which adds a table row at thebottom of any given table. The code takes into the consideration tbody tag andalso can be used as a jQuery plugin.

Recently I was asked to write a jQuery or JavaScript code that removes thelast/bottom row from the given table. The jQuery code I wrote was surprisinglysmall.

jQuery code to remove bottom/last table row

// Simple bottom row removal

$('#myTable tr:last').remove();

// Removing n'th (ex. 3rd) row from the table

$('#myTable tr:eq(2)').remove();

Improved jQuery code

We can improve our simple bottom row removal code to take into theconsideration the possible <tbody> and <tfoot> HTML tags that can be found intables.

// Improved code that takes into the consideration

// the <tbody> tag

$('#myTable').each(function(){

if($('tbody', this).length > 0){

$('tbody tr:last', this).remove();

}else {

$('tr:last', this).remove();

}

});

// Improved code that for n'th row removal

// In this example we are removing 3rd row

$('#myTable').each(function(){

if($('tbody', this).length > 0){

$('tbody tr:eq(2)', this).remove();

}else {

$('tr:eq(2)', this).remove();

}

});

Bonus JavaScript function

You can also turn the code above into the jQuery plugin or JavaScript function.Here is a JavaScript function to remove the bottom table row (you canamend the code to make it remove n’th row).

POSTED BY UZBEKJON AT 11:45 PM 5 COM M ENTSLABELS: ATTRIBUTES, EV ENTS, HOW TO, HTM L, T IP , TUTORIAL, W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 33/73

Page 34: JQuery HowTo

/*

Remove the last/bottom table row

*/

function removeTableRow(jQtable){

jQtable.each(function(){

if($('tbody', this).length > 0){

$('tbody tr:last', this).remove();

}else {

$('tr:last', this).remove();

}

});

}

// Here is how to use it

removeTableRow($('table'));

Also the above javascript function can easily be rewritten as a jQuery plugin.Read this post to learn how to create jQuery plugins.

Coupure de page insérée par AutoPager. Page ( 9 ).

W E D NE S D A Y, A P R I L 2 9 , 2 0 0 9

jQuery Twitter API plugin

UPDATE: Plugin has been updated! For more up to date informationread this post.

You might have noticed that I am talking and spending more time on Twitterlately. I have been helping Twitter users with their jQuery related questions andproblems as well. If you are using Twitter and have some kind of jQuery relatedquestion I will be happy to help.

Anyway, after I found a Twitter JSON(P) API url last week, I spent some timeplaying with it and ended up with a jQuery plugin that when given a Twitterusername retrieves and returns javascript object with user detials such asfollowers & following counts, full name, homepage URL, etc.

Download jQuery Twitter API - jTwitter here. Update: Now plugin also get any number of any user's posts.

Here is an example of returned JavaScript object:

// Starting from version 1.1 plugin gets user posts

// the returned object has changed. See update.

{

"screen_name":"jqueryHowto",

"name":"jQuery HowTo",

"description":"jQuery and javascript howtos, tutorials, h

acks, tips and performanace tests. Ask your jQuery questions here

...",

"url":"http://jquery-howto.blogspot.com",

"followers_count":294,

"friends_count":120,

"favourites_count":0,

"statuses_count":154,

"location":"",

"id":26767000,

"time_zone":"Central Time (US & Canada)",

"profile_image_url":"http://s3.amazonaws.com/twitter_prod

uction/profile_images/110763033/jquery_normal.gif",

"notifications":false,

"utc_offset":-21600,

"following":false,

"protected":false,

"created_at":"Thu Mar 26 14:58:19 +0000 2009",

"profile_link_color":"0000ff",

"profile_sidebar_fill_color":"e0ff92",

POSTED BY UZBEKJON AT 7: 57 AM 2 COM M ENTSLABELS: DOM , HO W TO, HTM L, JAV ASCRIPT, JQ UERY, M A NIPULATION, PLUGIN, T IP ,TUTORI AL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 34/73

Page 35: JQuery HowTo

"profile_background_tile":false,

"profile_sidebar_border_color":"87bc44",

"profile_background_color":"9ae4e8",

"profile_text_color":"000000"

"profile_background_image_url":"http://static.twitter.com

/images/themes/theme1/bg.gif",

}

As you can see the jQuery Twitter API plugin returns Twitter user's avatar URLas well. Using this jQuery plugin you could create another plugin that wouldreturn Twitter user's avatar image.

Y ou can see example usage and demo here.

Here is how to use jTwitter:

// I am query data for "jqueryHowto" user

$.jTwitter('jqueryHowto', function(userdata){

//Callback functn with the user data as shown above

$('#profile input.url').val(userdata.url);

$('#profile #avatar').html('<img src="'

+ userdata.profile_image_url + '" />');

});

The first parameter is a Twitter username and the second is a callback functionthat will be called after jQuery gets user details from the Twitter servers.

T U E S D A Y, A P R I L 2 8 , 2 0 0 9

Lock user interface plugin – uiLock

I was asked to create a user interface locker using jQuery. The main idea behindwas to lock all user interactions with the website while jQuery AJAX loadsblock contents and unlock when content is loaded. So I thought I would sharethe code and released it as a jQuery plugin called uiLock.

The plugin extends jQuery and adds two main functions called $.uiLock(); and$.uiUnlock();

Here is how to use uiLock jQuery plugin:

// To lock user interface

$.uiLock();

// To unlock user interface

$.uiUnlock();

$.uiLock(); takes an HTML text argument that will be placed in the pageoverlay. You can style the overlaying layer using CSS. You can change fontcolor, background color, etc. To style uiLocker use #uiLockId CSS selector.

For example:

#uiLockId{

background-color:red !important;

}

The plugin demo can be found in the plugin archive. Here is a screenshot of theplugin at work:

POSTED BY UZBEKJON AT 5: 29 AM 17 COM M ENTSLABELS: AJAX , JQUERY, JSON, PLUGIN

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 35/73

Page 36: JQuery HowTo

User will not be allowed to interact with the website on the screenshot above.Basically, we are blocking all user actions with an extra layer that uiLock jQueryplugin adds.

Download uiLock jQuery plugin here.

F R I D A Y , A P R I L 2 4 , 2 0 0 9

Twitter JSON/JSONP API URL

It is Friday and we don’t want to read long posts and tutorials. So today’s post isgoing to be short and sweet. I’ve been playing a lot with Twitter lately. I wrotesome jQuery and javascript functions that get user details, etc. I will share it withyou next week.

But for today, I would like to share Twitter’s JSON and JSONP API URL. I amsharing it because it was hard to find it first. I actually wrote a jQuery plugin thatgets Twitter user details using my previous post on cross site AJAX queryingmethod. All Twitter API usage tutorials and articles I found on internet werebased on RESTful non JSONP API, so I though I'll share Twitter JSON(P) APIwith you. Anyway...

Twitter JSON(P) API URL:

http://twitter.com/status/user_timeline/USERNAME.json?count=10

&callback=JSONPcallbackFunction

Here is a code to use with jQuery’s $.getJSON() function:

http://twitter.com/status/user_timeline/USERNAME.json?count=10

&callback=?

We have put ? (question mark) for callback function name so jQuery couldreplace it with a dynamic one that it has created.

Update: Check out jQuery Twitter API plugin – jTwitter, that usesthis Twitter API.

T U E S D A Y, A P R I L 2 1 , 2 0 0 9

AJAX update content every X seconds

I was asked several times on Twitter how to update some web page sectionor a block content on a page every x seconds. Some real life examples ofthis functionality are Twitter search results that come out when there are newtweets with search keyword or bit.ly real time link tracking that updates it’scharts every 5 seconds.

It is clear without saying that we are going to update our page content usingAJAX and of course we love AJAX in jQuery flavor. So key to this functionality is

POSTED BY UZBEKJON AT 8: 26 AM 1 COM M ENTSLABELS: AJAX , HO WTO , JQ UERY, PLUGIN, TOOLS, W ORKAROUND

POSTED BY UZBEKJON AT 1: 06 AM 2 COM M ENTSLABELS: AJAX , JSON, LI NK, REFERENCE, RESO URCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 36/73

Page 37: JQuery HowTo

JavaScript's built-in setInterval() function. It lets you to run some javascriptfunction every X seconds. For example, the following code would pop alert boxevery five seconds:

setInterval( "alert('Hello')", 5000 );

Now consider we want to update shouts in our shoutbox every 10 seconds.

function updateShouts(){

// Assuming we have #shoutbox

$('#shoutbox').load('latestShouts.php');

}

setInterval( "updateShouts()", 10000 );

The code above will run every 10 seconds (10,000 ms) and update the contentsof #shotbox with new shouts.

T H UR S D A Y, A P R I L 1 6 , 2 0 0 9

Get geographical location (geolocation) by IPaddress using jQuery

Today I came across this post called “IP Address Geolocation Javascript API :JSON”. The author provides you with a free geolocation query URL. The APIreturns the geographical location of the queried IP address with some additionalinformation such as:

{

'status':'ok',

'IP': '74.125.45.100',

'CountryCode': 'US',

'CountryName': 'United States',

'RegionName': 'California',

'ZipPostalCode': '94043',

'City': 'Mountain View',

'Latitude': '37.4192',

'Longitude': '-122.057'

}

// In case of an error

{

'status':'parent server not responding'

}

Update: the URL has been changed!

The JSON geolocation querying API’s address is:

http://iplocationtools.com/ip_query.php?output=json&ip=80.80.214.9

3

The URL above is dead, instead use this one:

http://www.geoplugin.net/json.gp?jsoncallback=?

And the great thing is, you can identify your website visitor’s IP and Geo locationby simply querying the API without any parameters like this:

http://iplocationtools.com/ip_query.php?output=json

Knowing your users’ IP and/or location, you might add a behavior to your websitethat is specific to some location. For example, offering some advertising to USonly visitors, or popup with special offer to European users.

Anyway, here is a sample jQuery code to query the API:

// Build the URL to query

var url = "http://iplocationtools.com/ip_query.php?output=json&ca

llback=?&ip=";

// Utilize the JSONP API

POSTED BY UZBEKJON AT 8: 08 AM 2 COM M ENTSLABELS: AJAX , HO WTO , JQ UERY, T IP , TUTORIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 37/73

Page 38: JQuery HowTo

$.getJSON(url, function(data){

if(data['status'] == 'ok'){

// Do something with the data

$('#profile #ip')

.append(data['IP']);

$('#profile #country')

.append(data['CountryName']);

}

});

Here we are not specifying any IP address in the url variable that is why it isgetting current user’s data.

Coupure de page insérée par AutoPager. Page ( 10 ).

W E D NE S D A Y, A P R I L 1 5 , 2 0 0 9

Shorten long URLs with jQuery & bit.ly service

I recently signed up to twitter and actively engaging with people who areinterested in jQuery. Twitter is a great service and there are all kinds ofdevelopers who are sharing interesting links and resources. So it is some kind ofinterest news group for me. Since you can only have 140 characters in your post,sharing long links limits you. URL shortening services to the rescue. There arelots of free URL shortening services, some are just for long URL shortening,some provide more features like real time click tracking, geostatistics and privateURLs.

The great thing about them is that they also provide you with an API. So Ithought that there is a way we can make a use of them in our jQuery code. Oneof the most popular services is bit.ly. You can read more about its API here.

I wrote a simple jQuery code that utilizes the service.

Here is an example:

(function($){

// set up default options

var defaults = {

version: '2.0.1',

login: 'bitlyapidemo',

apiKey: 'R_0da49e0a9118ff35f52f629d2d71bf07',

history: '0',

longUrl: ''

};

// Build the URL to query

var daurl = "http://api.bit.ly/shorten?"

+"version="+defaults.version

+"&longUrl="+defaults.longUrl

+"&login="+defaults.login

+"&apiKey="+defaults.apiKey

+"&history="+defaults.history

+"&format=json&callback=?";

// Utilize the bit.ly API

$.getJSON(daurl, function(data){

// Make a good use of short URL

$('#myContainer')

.append(data.results[url].shortUrl);

});

})(jQuery);

This code does not do much, but I hope you will find a good use of it in your ownapplications.

POSTED BY UZBEKJON AT 3: 12 AM 14 COM M ENTSLABELS: AJAX , HO WTO , JAV ASCRI PT, JQUERY, RESOURCE, T IP , TOO LS, TUTORIAL

POSTED BY UZBEKJON AT 5: 50 AM 6 COM M ENTSLABELS: AJAX , HO WTO , JAV ASCRI PT, JQUERY, REFERENCE, T IP , TOO LS, TUTORI AL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 38/73

Page 39: JQuery HowTo

M O ND A Y, A P R I L 1 3 , 2 0 0 9

Cross domain AJAX querying with jQuery

This post IS NOT about jQuery’s JSONP support. This post is about how tomake AJAX queries to domains other then yours. Basically how to achievecross domain scripting with jQuery. The technique will help you resolve theaccess to restricted uri denied" code: "1012 problem.

UPDATE: If you want to get cross-domain RSS feeds, there is abetter way to do that with universal RSS to JSON converter.

Using this method for cross site scripting you will be able to:

1. Make AJAX queries to any domain even those that differ from your own;2. Use any of $.get(), $.post(), $.ajax(), $getScript(), etc. jQuery

AJAX functions as your query method.

But all these does not come free, you will need to put a proxy to between youand the rest of the world. This cross domain querying solution works becauseyou actually loading the content from your own domain. You request the URLand the proxy script on your server actually loading the content from the internetand passing it over to you.

I created a sample PHP proxy that I used to get related news RSS feed for oneof my projects.

The PHP script to use as a cross domain scripting proxy:

<?php

// Set your return content type

header('Content-type: application/xml');

// Website url to open

$daurl = 'http://feeds.feedburner.com/jQueryHowto';

// Get that website's content

$handle = fopen($daurl, "r");

// If there is something, read and return

if ($handle) {

while (!feof($handle)) {

$buffer = fgets($handle, 4096);

echo $buffer;

}

fclose($handle);

}

?>

I named the file proxy.php and made my AJAX request to this url. Here is ajQuery code example:

$("#rssFeeds").load("path/to/proxy.php", function(){

// Some callback functions

});

And this is how I overcame the jQuery cross site scripting problems. The badnews is that not all web hosting companies allow fopen() to other domains, butenable it on request. My web server was very strict on security but the scriptabove worked well on it.

For fetching RSS feeds, use a better solution with universal

RSS2JSON converter.

S A T UR D A Y, A P R I L 1 1 , 2 0 0 9

jQuery image swap or How to replace an image

POSTED BY UZBEKJON AT 8: 05 AM 30 COM M ENTSLABELS: AJAX , ERROR, HOW TO , JAV ASCRIPT , JQUERY, T IP , W O RKAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 39/73

Page 40: JQuery HowTo

with another one using jQuery

Swapping one image with another is probably one of the most used javascripttechniques. Also Dreamweaver made “image replacement” even easier for nonHTML/Javascript programmers by including this feature out of the box. One thingabout Dreamweaver’s image swapping javascript is that it’s not the most beautifuljavascript code. Well, as always with anything javascript related, jQuery is to therescue.

jQuery makes dynamic image swapping a peace of cake. All you need to do toreplace your image with another one is to replace its src attribute. Thebrowser will take care of the rest.

Here is an example:

$("#myImage").attr("src", "path/to/newImage.jpg");

In the code above we are:

1. Selecting an image to be replaced;2. Changing its src attribute to the new replacer image’s URL.

TIP: To avoid page jumping and improve user experience it is a good idea to preloadyour images before you swap them.

F R I D A Y , A P R I L 1 0 , 2 0 0 9

Select text in input box on user select or focus

A colleague of mine who is not very javascript or for that matter jQuery awareasked me to help him to do a little trick with jQuery. He needed to select thecontents of the input box when user selects it (when onfocus event is firedbasically).

Selecting a text in your inputbox on focus is easy and actually 3 lines of jQuerycode, but it add a nice usability touch to your site. This “select all” behavior isdefault in browser when you browse through form fields using TAB key, but whenyou click on to the input text field it does not behave like that.

jQuery code to select text inside an input field on userclick or focus:

$("#myInputField").focus(function(){

// Select input field contents

this.select();

});

// Add this behavior to all text fields

$("input[type=text]").focus(function(){

// Select field contents

this.select();

});

TIP: Change the selector in the second example and get this behavior to passwordfields, textarea fields, etc.

Also we can add a little spice into our code and only select the contents of ourtext field or textarea if it has not been changed from its default original value.

// Let's add it to textarea this time

$("textarea").focus(function(){

// Check for the change

if(this.value == this.defaultValue){

this.select();

}

});

The code above selects all text content of textareas if and only if it’s value has

POSTED BY UZBEKJON AT 4: 18 AM 0 COM M ENTSLABELS: ATTRIBUTES, HO W TO, HTM L, JQ UER Y, M ANIPULATION, T IP , TUTORIAL

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 40/73

Page 41: JQuery HowTo

changed from the original one. This behavior would probably be more useful oninput fields :)

T H UR S D A Y, A P R I L 9 , 2 0 0 9

How to make jQuery / Prototype / MooTools &others play nicely with Smarty

Smarty is the first template engine I have learned and used in my projects.Smarty makes your PHP code cleaner and promotes the V in MVC. Here is anexample of Smarty template:

<html>

<head>

<title>User</title>

</head>

<body>

User Information:<br />

Name: {$name}

</body>

</html>

Smarty will replace the {$name} with the variable that you set in your PHP code.Anyway, do you see the problem that might arise when you try to embed yourjQuery code or any other javascript library (like Prototype, MooTools, Extjs, etc.)that uses $ as a function name in the <head>?

Smarty parses the file and whenever it encounters the {$ it would try to parse itand replace with the PHP variable like in this example here:

<html>

<head>

<title>User</title>

<script type="text/javascript">

$(document).ready(function(){

$(".clazz").css("color", "red");

});

</script>

</head>

<body>

User Information:<br />

Name: {$name}

</body>

</html>

The problem:

Smarty would not care that { and $ are on different lines and would see it like{$(".clazz.... The code above would cause this Smarty error:

Fatal error: Smarty error: [in templateFile.tpl line 5]: syntax error:unrecognized tag: $(".clazz").css("color", "red");(Smarty_Compiler.class.php, line 455) inC:\PHP\smarty\libs\Smarty.class.php on line 1092

The solution:

There are couple of things you can do about this problem:

1. Move your javascript (jQuery, Prototype, etc.) code into the external .jsfile.

2. Use jQuery() instead of $().3. Use Smarty’s {literal}...{/literal} directives to tell Smarty parsing

engine that it should not interpret the code within the block.

Example:

POSTED BY UZBEKJON AT 7: 27 AM 1 COM M ENTSLABELS: EV ENTS, HOW TO , HTM L, JQUERY, REFERENCE, T IP , W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 41/73

Page 42: JQuery HowTo

Here is how we can rewrite our javascript code above using the 3rd tip:

<html>

<head>

<title>User</title>

<script type="text/javascript">

{literal}

$(document).ready(function(){

$(".clazz").css("color", "red");

});

{/literal}

</script>

</head>

<body>

User Information:<br />

Name: {$name}

</body>

</html>

Coupure de page insérée par AutoPager. Page ( 11 ).

M O ND A Y, A P R I L 6 , 2 0 0 9

Display loading GIF image while loading throughAJAX

Well, let's face it, AJAX is everywhere. Nowadays clients want AJAX "enabled"web applications. They want their web sites to be Web2.0 and that is usuallyassociated with using AJAX. No doubt using AJAX to load parts of your page anduse more javascript effects, made easy by jQuery, is a great way to bring yourwebsite to life. But we should not forget about our users and the websiteusability. That is why it is a good practice to display something like text or imagethat informs users that the content is being loaded or processed.

Now, let's see how can we display a loading image while requested content isbeing loaded by one of the jQuery's AJAX functions. Here is what happens:

1. Something triggers AJAX request (like "search" button click);2. We put the loading image or a text that ask for user patience to the place

where we would later insert the loaded content (or anywhere else);3. After remote content is fully loaded, we remove/hide the loading

image/text and insert the loaded content.

To make it more apparent, imagine we have HTML page with this markup:

<button id="btnLoad">Load Content</button>

<div id="content">

Please click "Load Content" button to load content.

</div>

We want to load content when a user clicks on the "Load Content" button. So weneed to bind a click event to that button first and make AJAX request only afterit is fired.

$("#btnLoad").click(function(){

// Make AJAX call

$("#content").load("http://example.com");

});

The above code loads contents from http://example.com into the <divid="content">. While the page is being loaded we want to display our animatedGIF image in the "content". So we could further improve our code like so:

$("#btnLoad").click(function(){

// Put an animated GIF image insight of content

$("#content").empty().html('<img src="loading.gif" />');

// Make AJAX call

POSTED BY UZBEKJON AT 12:24 AM 6 COM M ENTSLABELS: ERRO R, HOW TO, JQUERY, T IP , W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 42/73

Page 43: JQuery HowTo

$("#content").load("http://example.com");

});

The .load() function would replace our loading image indicator with the loadedcontent.

Final note:

You might be using jQuery’s other AJAX functions like $.ajax(), $.get(),$.post(), in this case use their callback function to remove loading image/textand append your loaded data.

If you have any question, please tweet me.

T H UR S D A Y, A P R I L 2 , 2 0 0 9

Problems with jQuery mouseover / mouseoutevents

Today I have a quick note for you that will probably save you time someday.Basically it’s a workaround for a bug when you have parent element with childrenelements and parent element has mouseover or mouseout event. Moving yourmouse over children elements may fire mouseout event of their parent. This iscaused by event bubbling / propagation and if you would like to have a quicksolution just read the solution at the bottom of this post. If you would like tounderstand it in more details please search Google for event propagation.

The problem:

When you have mouseover and mouseout events bound to some element on youpage with children elements. Hovering over children element fires parent’smouseover and/or mouseout event.

The solution:

The solution to this error is to use mouseenter and mouseleave events instead ofmouseover and mouseout.

The reason:

This solution works because mouseover and mouseout events do not bubble fromchild to parent element.

W E D NE S D A Y, A P R I L 1 , 2 0 0 9

jQuery AJAX functions (load(), $.get(), etc.) arenot loading new page versions problem

Today I would like to share with you a quick solution to the common problemwhen your AJAX calls to some page that changes over time is not being loadedto your page. In other words, jQuery or your browser is not loading new version ofthe page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users Ibelieve, do not experience this problem. Usually it occurs when you use jQueryAJAX functions in javascript setInterval() method. Basically, what happens is thatFirefox can not see the changes been made to the page and thinks it’s the samewith the old one. So Firefox loads it from cache and you don’t see the newversion of your page. To resolve this issue, you should simply add a randomstring to the request like below.

The solution:

// Reload mypage.html every 5 seconds

var refresh = setInterval(function()

POSTED BY UZBEKJON AT 5: 23 AM 17 COM M ENTSLABELS: AJAX , HO WTO , HTM L, T IP , TUT ORIAL

POSTED BY UZBEKJON AT 4: 56 AM 24 COM M ENTSLABELS: EV ENTS, JQUERY, T IP , W ORKAR OUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 43/73

Page 44: JQuery HowTo

{

// Minimized code, suggested by Kovacs

$('#mydiv').load("mypage.htm?" + 1*new Date() );

}, 5000);

M O ND A Y, M A R C H 3 0 , 2 0 0 9

Use different CSS rules / styles in JavaScript orjQuery enabled browsers

This is a simple yet very useful and powerful technique. Using different CSS rulesin JavaScript or jQuery enabled browsers lets you customize your website stylefor JS enabled and disabled browsers using only CSS. Thus you separateconcerns of styling and business logic into CSS and javascript. This lets youconcentrate on your goals and not styling in your javascript code for example.

All you need to do is to add some class or id to body element usingjavascript/jquery to specify that javascript/jQuery is available. Then define tworules in you CSS files for js enable and disabled browsers.

Here is an example for Javascript enabled browser:

document.getElementsByTagName("body")[0].setAttribute("class", "j

s");

And in your CSS file:

.someClass{

display:block;

}

.js .someClass{

display:none;

}

Why do I need to have a different CSS styles for jQuery/javascript enabledbrowser you might ask. Consider you have a drop-down menu on your website’ssidebar and you would like to use jQuery/Javascript to make it drop down onmouse hover. You don’t want to hide (display:none) all submenus’ by default.That would make your website not accessible if user has disabled Javascript onhis/her browsers.

Similar to previous example, we can use difference CSS style for jQuery enabledbrowsers.

if(jQuery){

jQuery("body").addClass("jq");

}

And in your CSS file:

.someClass{

display:block;

}

.jq .someClass{

display:none;

}

S UN D A Y, M A R C H 2 9 , 2 0 0 9

“jQuery HowTo” on Twitter

Lately there is a lot of buzz about Twitter. It seems everybody is on Twitter,twittering… So I started investigation what all that buzz was about and what Icould have done with it. Several days later I found myself twittering.

Twitter is a great place to build your community of interest. For example if youare interested in jQuery than you can follow people who share tweets about

POSTED BY UZBEKJON AT 3: 29 AM 11 COM M ENTSLABELS: AJAX , ERROR, HOW TO , INS IG HTS, JAV ASCRIPT, JQUERY, T I P , W OR KAROUND

POSTED BY UZBEKJON AT 7: 18 AM 4 COM M ENTSLABELS: CSS , HOW TO, HTM L, JAV ASCRIPT, JQUERY, T I P , W OR KAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 44/73

Page 45: JQuery HowTo

jQuery/JavaScript and follow them. Examples could be the official jQuery andjQuery HowTo accounts.

Also, you can use WeFollow service to find people to follow by their interests.There are lots of other services that utilize Twitter API and provide great services.I added retweet button to my posts. If you like them, please retweet.

Coupure de page insérée par AutoPager. Page ( 12 ).

T H UR S D A Y, M A R C H 2 6 , 2 0 0 9

Check if jQuery plugin is loaded

The previous post checked if jQuery is loaded, now it is time to check if particularjQuery plugin is loaded. Checking if plugin exists or if plugin has been alreadyloaded is useful if you are writing your jQuery code that depends on that plugin.

Here is how to check if some jQuery plugin is loaded or not:

if(jQuery().pluginMethod) {

//jQuery plugin exists

} else {

//jQuery plugin DOES NOT exist

}

As you know from previous post on namespacing javascript plugins are createdas an additional namespace within jQuery namespace. All you have to do tocheck if plugin exists is to check if it’s namespace / function is defined.

For example, let’s assume that my plugin depends on jQuery Validation plugin.To check if validation plugin is loaded I would do the following:

if(jQuery().validate) {

// Validation plugin exists

// Now I can use $('#someId').validate()

} else {

// Validation plugin DOES NOT exist

}

W E D NE S D A Y, M A R C H 2 5 , 2 0 0 9

Adding and using jQuery on Blogger / Blogspot

Investigating my visitors statistics, I noticed that there were some users whowere interested in adding and using jQuery on their Blogger.com (Blogspot.com)accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. Allyou have to do is to add one line of code to your template’s header.

Here is the code to add to your blogger template’s header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jq

uery.min.js" type="text/javascript"></script>

NOTE: You don’t even need to upload jquery.js file on any other hosting Google will hostit for your.

Instruction for adding jQuery to Blogger:

1. Login to your dashboard;2. Choose your blog;3. From the top menu select “Layout”;4. Then select “Edit HTML” sub-menu;5. Add the above code just below <head> tag (or alternatively, just above

</head> tag)

POSTED BY UZBEKJON AT 10:34 PM 0 COM M ENTSLABELS: NEW S

POSTED BY UZBEKJON AT 4: 06 AM 7 COM M ENTSLABELS: HOW TO, INS IGHT S, JQUERY, PLUGIN, T IP , W ORKARO UND

POSTED BY UZBEKJON AT 5: 19 AM 5 COM M ENTSLABELS: HOW TO, JQUERY, T IP , W ORKAR OUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 45/73

Page 46: JQuery HowTo

T U E S D A Y, M A R C H 2 4 , 2 0 0 9

Check if jQuery.js is loaded

This is the very basics of any programming language, checking if some class,method, variable or property does already exist. In our case the programmingenvironment is JavaScript and the object we are checking for existence isjQuery() / $() function.

This method is not limited to jQuery only, you can check for anyother variable or function in your javascript.

Anyway, jQuery() or $() functions will only be defined if they are already loadedinto the current document. So to test if jQuery is loaded we can use 2 methods.

Method 1:

if (jQuery) {

// jQuery is loaded

} else {

// jQuery is not loaded

}

Method 2:

if (typeof jQuery == 'undefined') {

// jQuery is not loaded

} else {

// jQuery is loaded

}

NOTE: Here we are checking for jQuery function being defined or not. This is a safe wayto check for jQuery library being loaded. In case you are not using any otherjavascript libraries like prototype.js or mootools.js, then you can also check for $instead of jQuery.

You can also check if particular jQuery plugin is loaded or not.

M O ND A Y, M A R C H 2 3 , 2 0 0 9

Dynamically creating input box/checkbox/radiobutton... does not work in Internet Explorer (IE)

While working on some project, trying to create a checkbox and radio buttondynamically using jQuery I came across a problem. Mozilla Firefox, Opera andSafari were creating and rendering my new checkboxes just fine, but InternetExplorer (IE6, IE7) did not create them. I spend half a day trying to figure outwhat is wrong with my jQuery or JavaScript code. Some hours later, I remember,I came across a post saying that IE can not create a general DOM input formelement and then assign it a type (checkbox, radio, text, password, etc)attribute.

What you need to do when you are creating a new checkbox or radio button setwith jQuery is to define the type attribute while creating like so:

$('<input type="checkbox" />');

// Create and then set any other attributes

$('<input type="checkbox" />').attr('id', 'newBox');

Problem:

Can not create a new input form fields using jQuery or newly created checkboxesand radio buttons are not displayed/created.

Solution:

To solve the problem you need to create an input field with type attributealready defined.

POSTED BY UZBEKJON AT 7: 07 AM 4 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, JQUERY, TEST, T I P , W OR KAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 46/73

Page 47: JQuery HowTo

F R I D A Y , M A R C H 2 0 , 2 0 0 9

jQuery UI 1.7.1 released

The first maintenance release for jQuery UI 1.7 has been released. You candownload jQuery UI 1.7.1 from the following links:

Uncompressed:http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.jsCompressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js

Coupure de page insérée par AutoPager. Page ( 13 ).

M O ND A Y, M A R C H 1 6 , 2 0 0 9

Only the last element is bound/inserted/etc. inyour javascript code’s “for” loop

There is a common problem when you use javascript for loop to bind an eventfunction or add a class that comes from looping selection’s attributes.

To make clear what I mean consider this example:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {

var id = lis[i].id;

lis[i].onclick = function () {

alert(id);

};

} // All li's get and alert the last li's id

There is no obvious code syntax nor logical problem in this code. But you stillwill get last li’s id in alert window whichever li you click.

The solution to this problem is to rewrite your code similar to this one:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {

var id = lis[i].id;

lis[i].onclick = function (the_id) {

return function () {

alert(the_id);

};

}(id);

}

Here, we are introducing another anonymous function which will be calledimmediately after it has been declared, because of the trailing () (in our case(id)) with the current id.

This solves the problem of all items in the loop getting the lastarrays/elements/etc. attribute value (id/class/etc.).

T H UR S D A Y, M A R C H 5 , 2 0 0 9

Convert javascript objects into arrays for betterperformance

jQuery Howto blog has many posts on your javascript and jQuery codeperformance. If you have read the last performance post named “5 easy tips onhow to improve code performance with huge data sets in jQuery” then you

POSTED BY UZBEKJON AT 7: 59 AM 5 COM M ENTSLABELS: DOM , ERROR, HOW TO , HTM L, JQ UERY, M ANI PULA TION, T IP , W ORKAROUND

POSTED BY UZBEKJON AT 5: 44 AM 0 COM M ENTSLABELS: JQ UERY UI , NEW S

POSTED BY UZBEKJON AT 6: 03 AM 5 COM M ENTSLABELS: EV ENTS, HOW TO , INS IG HTS, JAV ASCRIPT, JQUERY, T I P , W OR KAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 47/73

Page 48: JQuery HowTo

probably got an idea that it’s better to work with arrays for better javascriptperformance.

The only problem is that jQuery returns an object not an array when you selectelements. Consider you have an object with lots of entries and you have toperform some manipulations that are available in javascript array such asreverse, sort, join, etc. Using built in methods is much faster then those youmight write yourself. So the best thing would be converting your objects to arraysand jQuery provides utility method that does exactly this –jQuery.makeArray(obj).

// From jQuery Documentation

var arr = jQuery.makeArray(document.getElementsByTagName("div"));

arr.reverse(); // use an Array method on list of dom elements

$(arr).appendTo(document.body);

F R I D A Y , F E B R U A R Y 2 7 , 2 0 0 9

Preload images with jQuery

Web2.0 came with AJAX and AJAX came with its own requirements andstandards for web application developers. Now web applications are more likedesktop applications with a lot of options, dialogs and more. If you havedeveloped AJAX application with different user controls you surely loadedresources such images, other javascript files on demand. This helps you keepyour application lightweight and makes its load time faster.

jQuery makes creation and loading DOM elements (in our case images) veryeasy. If you need to preload an image you can use this jQuery script here:

// Create an image element

var image1 = $('<img />').attr('src', 'imageURL.jpg');

First jQuery creates a image DOM element and setting the src attribute of theimage element would tell the user browser to load that image. Thus preloadingthe image.

Next you should insert your DOM element into the DOM tree using one of themany jQuery DOM manipulation methods.

Here are some examples of how you could insert preloaded image into yourwebsite:

var image1 = $('<img />').attr('src', 'imageURL.jpg');

// Insert preloaded image into the DOM tree

$('.profile').append(image1);

// OR

image1.appendTo('.profile');

But the best way is to use a callback function, so it inserts the preloaded imageinto the application when it has completed loading. To achieve this simply use.load() jQuery event.

// Insert preloaded image after it finishes loading

$('<img />')

.attr('src', 'imageURL.jpg')

.load(function(){

$('.profile').append( $(this) );

// Your other custom code

});

Similar how to’s:

Replace one image with another, swapping images.

W E D NE S D A Y, F E B R UA R Y 2 5 , 2 0 0 9

POSTED BY UZBEKJON AT 10:29 PM 3 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, JQUERY, M ANIPULATION, PERFORM ANCE, T IP ,W ORKARO UND

POSTED BY UZBEKJON AT 6: 27 AM 16 COM M ENTSLABELS: EV ENTS, HOW TO , JQUERY, M ANIPULATIO N, T IP , W O RKAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 48/73

Page 49: JQuery HowTo

How to add more items to the existing jQueryselection

There are occasions when you have already selected elements and need to addmore items to it. Imagine you have selected different items and have jQueryselection object. For example:

var elms = $('#elem, .items');

Now, you need to add more new items (DOM nodes) to your section. Let’s sayyou want to add .otherItems to your elms selection. You could achieve it byusing one of these methods:

elms.add('.otherItems');

$('.otherItems').add(elms); // The same as above

The post title for the second method would be “How to add jQueryobject/selection to the existing selection”. Anyway, it’s just wording :)

T U E S D A Y, F E B R U A R Y 2 4 , 2 0 0 9

jQuery For Firebug

We all use Firebug and sometimes need jQuery in pages that don’t already haveit. In such cases you can use the following javascript code or the bookmarkletthat would insert jQuery into the page’s DOM on the fly. Thus making jQueryavailable for use in Firebug.

Load jQuery to Firebug

Here are two options to jQuerify any page. The code is taken from a jQuerifyjavascript code snippet by John Resig.

Method 1: You can run this code to make jQuery available in Firebug:

var s = document.createElement('script');

s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquer

y/1.3.1/jquery.min.js');

document.body.appendChild(s);

s.onload=function(){

/*Your Code Here*/

};

void(s);

Method 2: Or you can drag this bookmarklet to your browser’s bookmarkstoolbar:

Load jQuery – When you click on this link it will load jQuery fromGoogle’s server and make it available in Mozilla add-on Firebug.

Coupure de page insérée par AutoPager. Page ( 14 ).

M O ND A Y, F E B R UA R Y 2 3 , 2 0 0 9

jQuery 1.3.2 Released

It seems that the jQuery’s new maintenance release 1.3.2 has not got enoughcoverage on other sites and thus a lot of developers still don’t know of it’srelease. It was released on the 20 of February and can be downloaded here:

Minified (gzipped 19KB)For development (120KB)

Notable changes:

Faster :hidden/:visible selectors;Faster .height()/.width() methods;Faster selectors in IE;

POSTED BY UZBEKJON AT 6: 12 AM 0 COM M ENTSLABELS: HOW TO, JQUERY, SELECTO RS, T IP , W ORKARO UND

POSTED BY UZBEKJON AT 6: 13 AM 1 COM M ENTSLABELS: FI REBUG , HO W TO, INS IGHTS, JQ UER Y, PLUGIN, T IP , TOOLS, W ORKAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 49/73

Page 50: JQuery HowTo

and now selectors return elements in their document appearance order;read release notes for more information on changes.

F R I D A Y , F E B R U A R Y 2 0 , 2 0 0 9

Add table row using jQuery and JavaScript

I noticed that there are a lot of developers who need to dynamically add a newtable row to the bottom of their tables. I wrote a little javascript function thattakes your jQuery selection of tables and dynamically adds a table row at thebottom of them.

jQuery add table row function definition:

/*

Add a new table row to the bottom of the table

*/

function addTableRow(jQtable){

jQtable.each(function(){

var $table = $(this);

// Number of td's in the last table row

var n = $('tr:last td', this).length;

var tds = '<tr>';

for(var i = 0; i < n; i++){

tds += '<td>&nbsp;</td>';

}

tds += '</tr>';

if($('tbody', this).length > 0){

$('tbody', this).append(tds);

}else {

$(this).append(tds);

}

});

}

jQuery add table row function usage example:

addTableRow($('#myTable'));

addTableRow($('.myTables'));

W E D NE S D A Y, F E B R UA R Y 1 8 , 2 0 0 9

How to use YUICompressor to compress yourjavascript code?

Since writing on this blog I posted two jQuery plugins and I needed to compressmy js files. So as jQuery documentation suggests I used YUICompressor.YUICompressor is javascript and CSS file/code compressor written in Javalanguage. So to run one yourself you will need JRE installed on your machine.

Then call this command:

java -jar /path/to/yuicompressor.jar path/to/file.js -o path/to/m

inimized.file.js

Your file will be compressed and saved to path you specified as the lastparameter (in our case minimized.file.js).

Links:

1. Download YUICompressor2. Download JRE (required to run java applications)3. Online version of YUICompressor

POSTED BY UZBEKJON AT 11:37 PM 0 COM M ENTSLABELS: JQ UERY, NEW S, PERFORM ANCE

POSTED BY UZBEKJON AT 4: 35 AM 2 COM M ENTSLABELS: DOM , HO W TO, HTM L, JAV ASCRIPT, JQ UERY, M A NIPULATION, T IP ,W ORKARO UND

POSTED BY UZBEKJON AT 3: 58 AM 3 COM M ENTS

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 50/73

Page 51: JQuery HowTo

M O ND A Y, F E B R UA R Y 1 6 , 2 0 0 9

Font cleartype problems with fadeIn() andfadeOut() in Internet Explorer 7 (IE7)

Have you ever noticed whenever you use jQuery's fadeIn() and fadeOut()functions your text will become edgy. Mozilla and other seem to be rendering fine(not sure about IE6). Anyway, to solve this problem you need to remove thefilter attribute from the DOM element that you have faded in/out.

For example:

// This causes this text glich

$("#message").fadeIn();

// This will fix it

document.getElementById("#message").style.removeAttribute("filter

");

Screenshots:

You need to remove the filter attribute after fadeIn() function has completed itsjob. In other words, as a function callback. Otherwise, fadeIn()/fadeOut()

functions would change the opacity of the element, which in turn would cause thefilter attribute to be attached yet again. So, remove the attribute in functioncallback like this:

$('#message').fadeIn(function(){

this.style.removeAttribute("filter");

});

S A T UR D A Y, F E B R UA R Y 1 4 , 2 0 0 9

New code highlighter for Blogger.com

Hi everyone. I've spent almost a whole day updating all my posts here on jquery-howto.blogspot.com with jQuery and javascript code. I am using lightweightGoogle Code Prettify to highlight my code. Here is an example of the newhighlighter:

function JavascriptFunction() {

// Comment example

var myVariable;

var privateMethod = function(){ };

return myVariable;

}

LABELS: CSS , HOW TO, INS IG HTS, JAV ASCRIPT, JQUERY, LINK, REFERENCE, RESOURCE,TIP , TOO LS

POSTED BY UZBEKJON AT 6: 56 AM 23 COM M ENTSLABELS: ANIM ATION, ERROR, HOW TO, HTM L, INS IGHT S, JAV ASCRIPT, JQUERY,M ANIPULATION, REFERENCE, T IP , W O RKAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 51/73

Page 52: JQuery HowTo

// jQuery code sample

$.extend({

myNamespaced: function(myArg){

return 'namespaced.' + myArg;

}

});

$.myNamespaced('A'); // Another comment

Coupure de page insérée par AutoPager. Page ( 15 ).

F R I D A Y , F E B R U A R Y 1 3 , 2 0 0 9

Automatically add table row count column to yourtables with jQuery rowCount plugin

Some time ago I wrote a javascript code that automatically adds table row countcolumn to your tables. And now I thought I would compile a jQuery plugin andsubmit it to the jQuery plugins repository.

Y ou can download jQuery rowCount plugin.

The script takes into consideration your table header's row and column spans.

Features:

Gracefully degrade for those browsers that do not support javascriptLets you keep your HTML mark up cleanMake your tabular data more usable and readable

Example code:

// Add row count

$('.myTables').rowCount();

// Provide your settings for

// column name and column style

var options = {

name: "Count",

cssClass: "countClass"

};

$('.myTables').rowCount(options);

Both options are optional. The only requirement is that you have to have<thead> and <tbody> tags in your table HTML.

Here is the original table (to the left) and new table (to the right) with row columnsautomatically added.

T H UR S D A Y, F E B R UA R Y 1 2 , 2 0 0 9

How to get a YouTube video screenshot image(thumbnail) URL using JavaScript

YouTube is a great video service by Google. As with any other product Googlemakes it easy to use its content on your own site. You can embed a YouTubevideo on your own site or query YouTube API (if you have a developer key). But

POSTED BY UZBEKJON AT 3: 42 AM 3 COM M ENTSLABELS: NEW S

POSTED BY UZBEKJON AT 3: 26 AM 2 COM M ENTSLABELS: HOW TO, HTM L, JQUERY, M ANIPULATIO N, PLUGI N

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 52/73

Page 53: JQuery HowTo

what if you don't want to embed a flash video player and you only need an imageof the video. The following function returns a YouTube video's thumbnail URL.Nothing more, nothing less.

Update: Now available as jQuery Y ouTube plugin – jY ouTube.

The javascript function:

function getScreen( url, size )

{

if(url === null){ return ""; }

size = (size === null) ? "big" : size;

var vid;

var results;

results = url.match("[\\?&]v=([^&#]*)");

vid = ( results === null ) ? url : results[1];

if(size == "small"){

return "http://img.youtube.com/vi/"+vid+"/2.jpg";

}else {

return "http://img.youtube.com/vi/"+vid+"/0.jpg";

}

}

You can pass a YouTube video URL or video id and the function will return apath to the video image. The second function argument is optional. You canspecify the size of returned image. It can be big (320x240) or small (128x96),defaults to big.

Here is an example usage:

imgUrl_big = getScreen("uVLQhRiEXZs");

imgUrl_small = getScreen("uVLQhRiEXZs", 'small');

See the plugin in action on jQuery Y ouTube demo page.

W E D NE S D A Y, F E B R UA R Y 1 1 , 2 0 0 9

How to set custom rules in jQuery Validationplugin for fields that have a period "." in theirnames

We all love and use jQuery Validation plugin. For basic forms it does a great joband works flawlessly 80% of the time. But we all work on different kinds ofprojects and validation requirements change project to project.

jQuery Validation is a very flexible plugin and provides a way to easily define yourown validation rules. You can read more about jQuery Validation plugin andcustom validation rules here. It is quite straight forward.

Anyway, I was working on a project that requires the use of custom rules and Ihad no control over the generated HTML code and used CSS selectors. So I hadto work with CSS classes that had period "." symbol in their names. My firstattempt failed.

Here is the code that failed. Pay attention to the selector name with the (.) in it'sname.

rules: {

user.email: {

required: true,

email: true

}

}

POSTED BY UZBEKJON AT 3: 59 AM 22 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, REFERENCE, T I P , W OR KAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 53/73

Page 54: JQuery HowTo

It is common in Java programming world that your form fields have periods (.) intheir names and this is an example of that. So to solve the problem all youhave to do is to make the object key a string like this:

rules: {

"user.email": {

required: true,

email: true

}

}

This will solve your problem and let you get on with your project. Happy coding...

M O ND A Y, F E B R UA R Y 9 , 2 0 0 9

5 easy tips on how to improve codeperformance with huge data sets in jQuery

Sitting on jQuery's support mailing list I noticed that developers use jQuery withhuge data sets and their code becomes very slow. Examples would begenerating very long tables with a lot of rows using AJAX to get JSON data. Oriterating through a long (very long) list of data, etc.

So I compiled a list of 5 easy tips on how to improve your code performancewhile working with huge data sets in jQuery.

1. Use JavaScript native for() loop instead of jQuery's $.each()helper function.

Native browser functions are always faster then any other helper functionsthat were built to add an abstraction layer. In case you are looping throughan object that you have received as JSON, I highly recommend yourewrite your JSON to contain an array rather than an object.

2. Do NOT append an element to the DOM in your loop.

This one is probably one of the most important tips that will significantlyimprove your code performance. It is so important that I will repeat myself.Do not append a new element to the DOM in your loop statement. Insteadstore it in a variable as text and append it to the DOM after your loopfinishes like this:

// DO NOT DO THIS

for (var i=0; i<=rows.length; i++)

{

$('#myTable').append('<tr><td>'+rows[i]+'</td></tr>');

}

// INSTEAD DO THIS

var tmp = '';

for (var i=0; i<=rows.length; i++)

{

tmp += '<tr><td>'+rows[i]+'</td></tr>';

}

$('#myTable').append(tmp);

3. If you have a lot of elements to be inserted into the DOM, surroundthem with a parent element for better performance.

When you have a lot of elements to insert into the DOM tree it takes timeto add them all. Somehow adding one element with 1000 children is fasterthan adding 1000 children separately. You can search this site forperformance tests that prove it. So, to improve our previous example's performance let's cover <tr>'s with<tbody> tag like this:

POSTED BY UZBEKJON AT 7: 11 AM 1 COM M ENTSLABELS: ERRO R, HOW TO, INS IGHTS, JQ UERY, PLUGIN, T IP , W ORKARO UND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 54/73

Page 55: JQuery HowTo

var tmp = '<tbody>';

for (var i=0; i<=rows.length; i++)

{

tmp += '<tr><td>'+rows[i]+'</td></tr>';

}

tmp += '</tbody>';

$('#myTable').append(tmp);

4. Don't use string concatenation, instead use array's join() methodfor a very long strings.

var tmp = [];

tmp[0] = '<tbody>';

for (var i=1; i<=rows.length; i++)

{

tmp[i] = '<tr><td>'+rows[i-1]+'</td></tr>';

}

tmp[tmp.length] = '</tbody>';

$('#myTable').append(tmp.join(''));

5. And the last but not least use setTimeout() function for your long listlooping and concatenation functions.

This will make sure that page does not freeze while it loops through thelong list of data and lets users to work with your page meanwhile.

It was well mentioned in comments that setTimeout() function should beused to split your code processing into little chunks so your browser doesnot freeze up like this:

function myFunk(data){

// do processing

if(!has_finished)

setTimeout("myFunk()", 100);

}

S A T UR D A Y, F E B R UA R Y 7 , 2 0 0 9

How to check jQuery version?

Sometimes you need to know what is the jQuery version that your script isworking with. This maybe useful in you jQuery plugins, so your code can utilizethe jQuery version specific code or maybe your code is running in someenvironment that already has jQuery embedded in, for example Drupal CMS.

Anyway, here are two ways you can check the current jQuery version.

// Returns string Ex: "1.3.1"

$().jquery;

// Also returns string Ex: "1.3.1"

jQuery.fn.jquery;

Coupure de page insérée par AutoPager. Page ( 16 ).

W E D NE S D A Y, F E B R UA R Y 4 , 2 0 0 9

How to disable all jQuery animations at once

Yesterday I came across jQuery.fx.off setting in jQuery documentation. It

POSTED BY UZBEKJON AT 7: 20 AM 16 COM M ENTSLABELS: DOM , HO W TO, INS IGHTS, JAV ASCRI PT, JQUERY, M ANI PULATI ON,PERFORM ANCE, RESOURCE, T I P , W O RKAROUND

POSTED BY UZBEKJON AT 12:33 AM 4 COM M ENTSLABELS: HOW TO, INS IGHT S, JQUERY, REFERENCE, T IP , W ORKAROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 55/73

Page 56: JQuery HowTo

disables all jQuery animations effective immediately when you set it's value totrue.

Consider this code:

jQuery.fx.off = true;

$("input").click(function(){

$("div").toggle("slow");

});

Your div will be showed/hidden immediately without animation. One of thereasons (as documentation mentions) to disable animations would be "slow"environments.

T U E S D A Y, F E B R U A R Y 3 , 2 0 0 9

Why should I include all my CSS files beforejQuery?

The simple answer is: "Because you have to". Since jQuery version 1.3 jQuerydoes not make sure all of your CSS files are loaded before it fires .ready()

event. Here is an excerpt from jQuery 1.3 release notes:

The ready() method no longer tries to make any guarantees aboutwaiting for all stylesheets to be loaded. Instead all CSS files shouldbe included before the scripts on the page.

This takes us to one more of our jQuery tips.

TIP: Include all your CSS files before jQuery file.

M O ND A Y, F E B R UA R Y 2 , 2 0 0 9

How to get full html string including the selectedelement itself with jQuery's $.html()

Sometimes you need to get the selected element's html as well when using.html() function. To make it more clear what I mean, consider you have thisHTML markup:

<div id="top">

<div id="inner">

Some content

</div>

More content

</div>

And you need to get not only <div id="inner">Some con... but <divid="top"><div id="inner">Some con...

Here is the code to get jQuery selector's HTML including its own:

var html = $('<div>').append($('#top').clone()).remove().html();

Here we are:

1. Cloning selected div

2. Creating a new div DOM object and appending created clone of the div

3. Then getting the contents of wrapped div (which would give us all HTML)4. Finally removing the created DOM object, so it does not clutter our DOM

tree.

This is a little trick you can use to select self HTML with jQuery's .html()

function. But if you can you should surround your markup with some dummy div

and avoid this workaround all together. This would be much faster since jQuery

POSTED BY UZBEKJON AT 4: 29 AM 1 COM M ENTSLABELS: ANIM ATION, EV ENTS, HOW TO , JQUERY, PERFO RM ANCE, REFERENCE, T IP

POSTED BY UZBEKJON AT 2: 25 AM 4 COM M ENTSLABELS: INS IGHTS, JQ UER Y, REFERENCE, T I P

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 56/73

Page 57: JQuery HowTo

would not need to do all the DOM manipulations.

F R I D A Y , J A NU A R Y 3 0 , 2 0 0 9

How to create a rounded corner box plugin withjQuery

Recently, we have redesigned one of our projects. The task was to make the webapplication to look and act more like Web2.0 app. New design looked great andsurely it had lot's of rounded corners.

Y ou can download jQuery Rounded Corners plugin.

First, rounded corners were done using CSS, but it got our code cluttered and itintroduced a lot of unnecessary HTML markup. Since we had full control of ourtarget audience's browsers and we were sure that they had JavaScript enabledbrowser we chose jQuery to do all the dirty work. All we have to do to define abox/table/anything to be in a rounded box is to give it a class "boxed" and therest is done with jQuery.

Here is the final rounded corners jQuery plugin code:

(function($){

$.fn.extend({

box: function() {

return $(this).each(function(){

$(this).wrap('<div class="box"><div></div><div class="tl"

></div><div class="tr"></div><div class="bl"></div><div class="br

"></div></div>');

});

}

})

})(jQuery);

CSS looks like this:

/* -- Rounded Box -- */

.box{position:relative;background-color:#eee;margin-bottom:25px;p

adding:10px;}

.box .tl,.box .tr,.box .bl,.box .br{position:absolute;width:10px;

height:10px;}

.box .tl{background-image:url(images/box-tl.gif);top:0;left:0;}

.box .tr{background-image:url(images/box-tr.gif);top:0;right:0;}

.box .bl{background-image:url(images/box-bl.gif);bottom:0;left:0;

}

.box .br{background-image:url(images/box-br.gif);bottom:0;right:0

;}

.box .bg-white{background-color:#fff;padding:10px;}

W E D NE S D A Y, J A N UA R Y 2 8 , 2 0 0 9

How to set default settings in your jQuery plugins

Recently we had a post about automatically adding row count to your tables andthen made a plugin out of it. We could further improve our plug-in by providing anoption to let plug-in users to overwrite default setting.

For example plugin users could provide a CSS class to set to the added columnor change the default "#" in the column header to some other meaningful text.

This is all possible by letting users of your plugin to provide their setting.

For example, in our table row count plugin, users could do this:

$('table').addCount({colName : 'Number'});

So this is how you do this:

POSTED BY UZBEKJON AT 3: 59 AM 13 COM M ENTSLABELS: DOM , HO W TO, JQ UER Y, M A NIPULATION, SELECTORS, T IP , WO RKAROUND

POSTED BY UZBEKJON AT 11:25 PM 6 COM M ENTSLABELS: HOW TO, JQUERY, PLUGI N

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 57/73

Page 58: JQuery HowTo

$.fn.addCount = function(options) {

// set up default options

var defaults = {

colName: '#',

colWidth: 100,

addCssClass: true,

colClass: 'mycolumn',

};

// Overwrite default options

// with user provided ones

// and merge them into "options".

var options = $.extend({}, defaults, options);

/*

If user provided only "colName"

option then default options for

other 3 variables will be added

to "options" variable.

*/

return this.each(function() {

/* Now you can use

"options.colWidth", etc. */

console.log(options);

});

};

The key line here is var options = $.extend({}, defaults, options); Thisline merges options and defaults variables adding missing properties inoptions variable from defaults variable.

Here is a great example from documentation page of jQuery.extend() thatgives a good example about $.extend() method.

var empty = {}

var defaults = { validate: false, limit: 5, name: "foo" };

var options = { validate: true, name: "bar" };

var settings = $.extend(empty, defaults, options);

Coupure de page insérée par AutoPager. Page ( 17 ).

M O ND A Y, J A NU A R Y 2 6 , 2 0 0 9

Namespace your JavaScript function andvariable with jQuery

We all know that global variable are evil. Namespacing your variables andmethods is now considered a good practice and shows your awareness aboutthe trends. Anyway, I thought how can I namespace my variables and methodsin jQuery. Well, first off, I can easily extend jQuery with custom written plugins.

$.fn.extend({

myNamespaced: function(myArg){

return 'namespaced.' + myArg;

}

});

jQuery().myNamespaced('A');

$().myNamespaced('A'); // Shorthand $()

// Outputs: namespaced.A

Now my functions are namespaced and would not conflict with any other alreadydeclared functions with the same name. This is great, but to access myfunctions or variables I have to call jQuery(). The code still looks like chainingnot namespacing. To declare your variables or functions in jQuery namespaceyou can extend the core jQuery object itself using jQuery.extend() rather thanjQuery.fn.extend().

POSTED BY UZBEKJON AT 3: 32 AM 0 COM M ENTSLABELS: HOW TO, INS IGHT S, JQUERY, PLUGIN, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 58/73

Page 59: JQuery HowTo

$.extend({

myNamespaced: function(myArg){

return 'namespaced.' + myArg;

}

});

jQuery.myNamespaced('A');

$.myNamespaced('A'); // Shorthand

// Outputs: namespaced.A

As you can see, now I can call my functions and properties without parenthesisafter jQuery object. Now my functions have a jQuery namespace and will notconflict with other functions that might have the same name.

TIP: Use $.extend({}) to namespace your fields and methods.

F R I D A Y , J A NU A R Y 2 3 , 2 0 0 9

Dynamically adding table row count numberusing JavaScript and jQuery

Now available as a rowCount jQuery plugin.

Recently on jQuery mailing list a user asked how he/she could add a row countin their table automatically. So I wrote a code snippet which looks like this:

$(document).ready(function(){

$("table").each(function(){

if($(this).is('table')){

$('thead th:first-child, thead td:first-child', this).each(

function(){

if($(this).is('td'))

$(this).before('<td>#</td>');

else if($(this).is('th'))

$(this).before('<th>#</th>');

});

$('tbody td:first-child', this).each(function(i){

$(this).before('<td>'+(i+1)+'</td>');

});

}

});

});

This code was for specific case, where there is only one table on the page and ithas only one row in its header. That is why I took into the account the possibilityof row spans and multi line rows in header and rewrote the code. Then made aplugin out of it.

So, here is the final code:

(function($){

$.fn.extend({

addCount: function() {

return $(this).each(function(){

if($(this).is('table')){

$('thead th:first, thead td:first', this).each(function

(){

if($(this).is('td'))

$(this).before('<td rowspan="'+$('thead tr').length

+'">#</td>');

else if($(this).is('th'))

$(this).before('<th rowspan="'+$('thead tr').length

+'">#</th>');

});

$('tbody td:first-child', this).each(function(i){

$(this).before('<td>'+(i+1)+'</td>');

});

}

});

POSTED BY UZBEKJON AT 6: 18 AM 8 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, JQUERY, OO P, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 59/73

Page 60: JQuery HowTo

}

});

})(jQuery);

To apply it to your tables use this code:

$('table').addCount();

$('.some-table-class').addCount();

$('#some-table-id').addCount();

W E D NE S D A Y, J A N UA R Y 2 1 , 2 0 0 9

Object-Oriented JavaScript, how to achievepublic properties/fields

Recently I posted my findings about private fields in JavaScript. So this is acontinuation of the post and it talks about public fields in your JavaScript code.So here is a quick example of public properties in your code:

function User() {

// Private property

var name = '';

return {

// Public property

classVersion: '1.3',

prevVersions: ['1.2.3', '1.2', '1'],

setName: function(newName) {

name = newName;

},

getName: function() {

return name;

}

};

}

var user = new User();

user.classVersion; // 1.3

user.prevVersions; // ['1.2.3', '1.2', '1']

NOTE: Define an object property name in your return statement and it will be accessiblefrom outside. In other words - public field.

Public and private methods in JavaScript

I have been talking about public and private properties so far. I guess it is time forprivate and public methods. The idea behind is the same. To make a methodpublic you need to define it in your return object and if you want to make it privateyou should declare it outside your return.

Basically:

function User() {

// Private variable

var name;

// Private method

var privateMethod = function(){

// Access to private fields

name += " Changed";

};

return {

// Public methods

setName: function(newName) {

name = newName;

privateMethod();

},

POSTED BY UZBEKJON AT 11:30 PM 5 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, JQUERY, M ANIPULATION, PLUGIN, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 60/73

Page 61: JQuery HowTo

getName: function() {

return name;

}

};

}

var user = new User();

user.setName("My Name");

user.getName(); // My Name Changed

As you can see, privateMethod and name are declared outside the return

object and thus they are made private. Variables declared inside the return objectare public and accessible using dot notation.

F R I D A Y , J A NU A R Y 1 6 , 2 0 0 9

jQuery 1.2.6 and jQuery 1.3 class selectorperformance benchmark

Reading about the jQuery 1.3's new selector engine Sizzle and its speedimprovements I thought I would do a performance comparison between jQuery1.2.6 and jQuery 1.3. I was prepared for something good, but the test resultsblew my mind.

I had a page with one unordered list with 1000 items each with a class(class="1", class="2", etc).

Here is are the tests and results:

console.time("testClass");

for(i=0;i<100;i++){

$('.'+i);

}

console.timeEnd("testClass");

/**

* jQuery 1.2.6

1235 ms

1326 ms

1342 ms

=======

1301 ms

*/

/**

* jQuery 1.3

54 ms

52 ms

53 ms

=======

53 ms

*/

As you can see the new selector engine is freakishly fast :) Actually with thisspecific test it is 25 times fast. Taking into the consideration that class selectionis one of the most used selectors, we can assume that our code will workconsiderably faster.

NOTE: I have performed the same tests with selection with id's. The result were exactlythe same (9 ms). Taking into the consideration that both versions of jQuery usebrowser's built in getElementById() function for ID selections, there is notmuch one can do to beat that.

T H UR S D A Y, J A NUA R Y 1 5 , 2 0 0 9

Working with jQuery 1.3's new Event object(jQuery.Event)

To start, in jQuery 1.3 event object has been normalized and wrapped intojQuery.Event object. As it says in the documentation: "The event object isguaranteed to be passed to the event handler (no checks for window.eventrequired)."

Here is an jQuery.Event object overview:

POSTED BY UZBEKJON AT 6: 34 AM 6 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, OO P, T IP

POSTED BY UZBEKJON AT 5: 18 AM 4 COM M ENTSLABELS: JQ UERY, PERFORM ANCE, SELECTORS, TEST

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 61/73

Page 62: JQuery HowTo

Attributes1. event.type2. event.target3. event.relatedTarget4. event.currentTarget5. event.pageX/Y6. event.result7. event.timeStamp

Methods1. event.preventDefault()2. event.isDefaultPrevented()3. event.stopPropagation()4. event.isPropagationStopped()5. event.stopImmediatePropagation()6. event.isImmediatePropagationStopped()

Now, how to work w ith jQuery.Event object?

Anonymous functions that were bind to your elements will receive this new(jQuery.Event) event object and can utilize it's new attributes and methods. Soyour previous code will work fine (most of the time :) ).

$("a").click(function(event) {

alert(event.type);

});

The fun part starts when you trigger events with jQuery.Event. You can createnew jQuery.Event object and give it to the trigger()'er to trigger that event.

Example:

// Create new event object

// the "new" is optional

var e = jQuery.Event("click");

// Add additional data to pass

e.user = "foo";

e.pass = "bar";

// Call your event

$("a").trigger(e);

NOTE: You don't have to use new to create a new jQuery.Event object. It is optional.

Alternative way to pass data through event object:

$("a").trigger({

type:"click",

user:"username",

pass:"password"

});

Try to play with the new event attributes and methods. You can do all kinds offun things with them. Example: event.result, event.relatedTarget.

Coupure de page insérée par AutoPager. Page ( 18 ).

W E D NE S D A Y, J A N UA R Y 1 4 , 2 0 0 9

jQuery 1.3 has been released!

Long awaited jQuery 1.3 has just been released. You can read about it on jQueryblog and release notes.

Notable changes:

new blazingly fast selectors engine (Sizzle)new jQuery.Event object that is available in your event functionsfaster HTML injection (~6x faster)

POSTED BY UZBEKJON AT 7: 14 AM 2 COM M ENTSLABELS: EV ENTS, HOW TO , INS IG HTS, JQUERY, R EFERENCE

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 62/73

Page 63: JQuery HowTo

.hide() and .show() are now much faster (~2.5x faster)[@attr] syntax deprecated, use [attr]and many many more. Please read release notes.

Pack and minimize your JavaScript code size

In pursue for my JavaScript code performance and some questions on jQuerymailing list I looked for and eventually came across some of the JavaScript codepackers. Here is a list of custom JavaScript code compressors available for free.

1. YUI Compressor (from Yahoo)2. JSMin (by Douglas Crockford)3. ShrinkSafe (from Dojo library)4. Packer (by Dean Edwards)

According to general opinion of developers on the net (and jQuery official site)you should use Yahoo's YUI Compressor to compress your jQuery andJavaScript code.

M O ND A Y, J A NU A R Y 1 2 , 2 0 0 9

How to check your JavaScript code for errors

There are times when you can't understand why your code is not doing what it'ssupposed to do. After killing half an hour on trying to figure out what is theproblem you either give up and decide to rewrite or leave it for later. Later lookingat your code you clearly see the bug and think how you couldn't you see it.

For cases like that you can use online JavaScript code validator JSLint.

F R I D A Y , J A NU A R Y 9 , 2 0 0 9

jQuery and HTML image maps

Most of us don't even use image maps anymore. But occasionally, mostly whenfreelancing, you will need to work with the pages that were created in mid 90'sand image maps where pop stars in that era. Anyway to refresh your memoryhere is how HTML image map looks like:

<img src="bigImage.gif" usemap="#parts" />

<map name="parts">

<area shape="rect" coords="20,6,200,60" href="http://www.boo.uz

">

<area shape="circle" coords="100,200,50" href="http://www.googl

e.com">

</map>

To access HTML image map area attributes and properties use something likethis:

$('area').click(function() {

var url = $(this).attr('href');

var coords = $(this).attr('coords').split(',');

// Your code here

// To prevent default action

return false;

POSTED BY UZBEKJON AT 7: 04 AM 0 COM M ENTSLABELS: JQ UERY, NEW S

POSTED BY UZBEKJON AT 6: 05 AM 5 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, JQUERY, LINK, PERFO RM ANCE, RESO URCE, T IP

POSTED BY UZBEKJON AT 4: 37 AM 0 COM M ENTSLABELS: ERRO R, HOW TO, JAV ASCRIPT, LI NK, RESOURCE, TEST

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 63/73

Page 64: JQuery HowTo

});

This is all that I have on jQuery and image maps.

T H UR S D A Y, J A NUA R Y 8 , 2 0 0 9

How to select innermost element with jQuery

Today I was working on new category browser UI for the project I am working. Ihad to select the innermost element and append some more content into it.Basically, I had an HTML like this:

<div>Outermost element

<div>Some Text

<div>Evenmore text

<div>Who cares anymore?

<div>Innermost Element</div>

</div>

</div>

</div>

</div>

So I needed to select the innermost div and append another div to it. There is nojQuery selector but you can use selectors that exist to achieve this goal. Theinnermost element would be the last div with the only-child.

$('div:only-child:last');

// Change background color to gray

$('div:only-child:last').css('background-color',"#ccc");

Coupure de page insérée par AutoPager. Page ( 19 ).

W E D NE S D A Y, J A N UA R Y 7 , 2 0 0 9

Object-Oriented JavaScript, how to achieveprivate properties/fields

The very basic of Object-Oriented Programming (OOP) is private fields and publicmethods (not considering features like polymorphism, inheritance, etc). So howto achieve this very basic of OOP in JavaScript. It turns out to be easy. Here ishow to have private fields in your custom JavaScript functions/classes and usingmethods of your function/class to amend it.

function User() {

var name = '';

return {

setName: function(newName) {

name = newName;

},

getName: function() {

return name;

}

}

}

var user = User();

user.setName("My Name");

user.getName(); // My Name

The User() class we just created could be considered a bean in Java. Using thistemplate you can have as many private fields and public methods as you want.

T U E S D A Y, J A NU A R Y 6 , 2 0 0 9

POSTED BY UZBEKJON AT 5: 14 AM 5 COM M ENTSLABELS: HOW TO, HTM L, JQUERY, REFERENCE, SELECTORS, T IP

POSTED BY UZBEKJON AT 3: 01 AM 2 COM M ENTSLABELS: HOW TO, JQUERY, SELECTO RS, T IP

POSTED BY UZBEKJON AT 6: 51 AM 2 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, OO P, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 64/73

Page 65: JQuery HowTo

How jQuery's plugin/extension system works

Recently I was reading about extending jQuery's functionality and plugin system.I wrote two articles on extending jQuery functionality with your own customfunctions. To extend you write $.fn.myFunction and then your function. It wasinteresting what $.fn is, so I look through the jQuery code and on line 33 found:

jQuery.fn = jQuery.prototype = {

So jQuery's fn is just a synonym for its prototype. I know this is not a discoveryof the century but it gives you some understanding of how jQuery's plug-insystem works and its insights.

M O ND A Y, J A NU A R Y 5 , 2 0 0 9

Improving jQuery code performance

Following jQuery performance related articles here is another tip to boost yourjQuery code performance. You should use ID selections whenever you can.Because jQuery uses browser's native getElementById() function which ismuch faster.

Now back to JavaScript code performance testing. I have an unordered list with1000 items. First test will have list items with class attributes and the secondlist will have id attributes set to its items.

console.time('test');

for (i = 0; i < 500; i++) {

$('.'+i);

}

console.timeEnd('test');

// ~8204ms

console.time('test');

for (i = 0; i < 500; i++) {

$('#'+i);

}

console.timeEnd('test');

// ~32ms

As you can see selecting with element's #id is much faster. In our case 256times (8204/32).

T U E S D A Y, D E C E M B E R 3 0 , 2 0 0 8

How to disable/enable an element with jQuerySometimes you need to disable or enable some elements in your document andjQuery makes this task easy. All you have to do is to set disabled attribute to"disabled".

Example:

// To disable

$('.someElement').attr('disabled', 'disabled');

In order to enable any disabled element you need to set the disabled attributeto empty string or remove it entirely like in the code below.

// To enable

$('.someElement').removeAttr('disabled');

// OR you can set attr to ""

$('.someElement').attr('disabled', '');

And that’s basically how to disable and enable HTML / DOM elements on yourwebsite using jQuery. You can see this code in action in real life example of

POSTED BY UZBEKJON AT 2: 28 AM 0 COM M ENTSLABELS: INS IGHTS, JQ UER Y, PLUGIN, REFERENCE

POSTED BY UZBEKJON AT 3: 16 AM 0 COM M ENTSLABELS: JQ UERY, PERFORM ANCE, SELECTORS, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 65/73

Page 66: JQuery HowTo

Disabling submit button on form submission post.

M O ND A Y, D E C E M B E R 2 9 , 2 0 0 8

Caching in jQuery

What is great about jQuery is its simplicity in selecting elements. We all use ithere and there, basically everywhere. This simplicity comes with its drawbacks.jQuery traverses through all elements every time we use selectors. So to boostup your jQuery application you should always cache your selections to somevariable (if you find yourself using the same selection more than once). In caseyou are not selecting an element more than once you should not cache yourselection by assigning it to some variable.

Here is an exam ple:

var cached = $('.someElement');

cached.addClass('cached-element');

Here are the performance tests:

console.time('test');

for (i = 0; i < 1000; i++) {

$('.the').text(i + ' ');

}

console.timeEnd('test');

// ~260ms

console.time('test2');

var the = $('.the');

for (i = 0; i < 1000; i++) {

the.text(i + ' ');

}

console.timeEnd('test2');

// ~30ms

As you can see caching increased performance by nearly 10 times.

Coupure de page insérée par AutoPager. Page ( 20 ).

M O ND A Y, D E C E M B E R 2 9 , 2 0 0 8

How to check if checkbox is checked usingjQuery

Note: If you are new to jQuery , you might find our short jQuerybeginner tutorials useful.

While working on my previous project I needed a way to check if the certaincheckbox is checked or not. jQuery is a great library but I had a hard timeidentifying if any particular checkbox was checked. So here is the way to do justthat.

All you need to do is to check checked attribute of checkbox HTML tag:

// First way

$('#checkBox').attr('checked');

// Second way

$('#edit-checkbox-id').is(':checked');

// Third way for jQuery 1.2

$("input[@type=checkbox][@checked]").each(

function() {

// Insert code here

}

POSTED BY UZBEKJON AT 1: 58 AM 15 COM M ENTSLABELS: ATTRIBUTES, BEGI NNER, HOW TO , JQUERY, M ANIP ULATI ON, REFERENCE, T IP

POSTED BY UZBEKJON AT 9: 47 PM 7 COM M ENTSLABELS: HOW TO, JQUERY, PERFORM ANCE, SELECTO RS, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 66/73

Page 67: JQuery HowTo

);

// Third way == UPDATE jQuery 1.3

$("input[type=checkbox][checked]").each(

function() {

// Insert code here

}

);

// In his comment Andy mentions that the 3rd method

// does not work in Firefox 3.5.2 & jQuery 1.3.2

First two methods return true or false. True if that particular checkbox waschecked or false if it is not checked. The third method iterates though allcheckboxes with checked attribute defined and performs some action.

See the latest jQuery tips. They are short, very short!

Want to learn how to check if jQuery.js is loaded into the current document?Also learn how to work with jQuery 1.3's new Event object.

F R I D A Y , D E C E M B E R 2 6 , 2 0 0 8

How to test JavaScript code performance

Sometimes after all day long coding your code becomes not so effective andyour code (usually interface related) becomes slow. You have done so manychanges and don't exactly know what slowing it down. In cases like this (and ofcourse, plenty other cases) you can test your JavaScript code performance. First of all, you need Firefox browser and Firebug web developers life saverplugin. I can not think of my web programming work without it.

Anyway, Firebug makes available console variable to your JavaScript page.Console can be used for logging or printing out debugging information to theFirebug console. Console also has one handy method for tracking time inmilliseconds.

console.time('timerName');

// Your javascript code to test here

console.timeEnd('timerName');

You can use this script to test your JavaScript code. timerName in the code canbe any name for your timer. Don't forget to end your timer using the same namefor timeEnd().

T H UR S D A Y, D E C E M B E R 2 5 , 2 0 0 8

Everything has characteristics of an Array inJavaScript

The title maybe a little misleading. So don’t confuse Arrays with Object inJavaScript! They have common and non-common methods. You can use jQuerybuilt-in method to check if any given variable is an array ($.isArray(var)).

I came across this feature of JavaScript recently and thought I would share it withyou. So every object I tried to use had capabilities of array. I could refer toobject/class members and properties using array syntax. For example:

var obj = new Number();

obj.name = "My Name";

alert(obj["name"]);

Similarly with your own classes:

function myFunk(){

this.name = "My Name";

POSTED BY UZBEKJON AT 4: 18 AM 19 COM M ENTSLABELS: ATTRIBUTES, BEGI NNER, HOW TO , HTM L, JQUERY, REFERENCE, T IP

POSTED BY UZBEKJON AT 4: 26 AM 0 COM M ENTSLABELS: FI REBUG , HO W TO, JA V ASCRIPT, PERFO RM ANCE, REFERENCE, TEST, T I P

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 67/73

Page 68: JQuery HowTo

}

var obj = new myFunk();

obj.newProperty = "Dynamicly Created";

obj.newMethod = function(){ return "Hello"; }

alert( obj["newMethod"]() );

Pay attention to dynamically created properties and methods. Pretty awesome :)

TIP: In case you want your methods to be available to all class instance useprototype.

T U E S D A Y, D E C E M B E R 2 3 , 2 0 0 8

What a heck is a (function ($){ ... })(jQuery)

Recently I wrote two articles on how to extend jQuery using its plug in systemand a shorthand for that. If you look into them closely they are actually the samething. The only difference being that the code in first one is wrapped in thisanonymous JavaScript function:

(function ($) {

// code goes here

})(jQuery)

Little research shows that this allows the use of $ within this function withoutconflicting with other JavaScript libraries who are using it. Basically, since we aresetting $ as a parameter, $ will overwrite any globally definedvariables/references of $ in that particular anonymous function.

// Assume "$" is a prototype reference

(function ($) {

// Here "$" is a jQuery reference

})(jQuery)

So basically it’s an anonymous function that lets jQuery play nicely with otherjavascript libraries that might have $ variable/function. Also if you notice, alljQuery plugins code is wrapped in this anonymous function.

NOTE: The following two javascript codes are equivalent:

// Code 1:

(function ($) {

// Javascript code

})(jQuery)

// Code 2:

var myFunction = function ($) {

// Javascript code

};

myFuntion(jQuery);

M O ND A Y, D E C E M B E R 2 2 , 2 0 0 8

How to add your own custom functions to jQuery

Recently I wrote a template on how to extend jQuery and how to create your ownfunctions. Since then I came across even smaller code snippet on how to addyour own custom functions, in other words how to create plugins for jQuery. Sowithout further ado:

$.fn.myFunction = function() {

return $(this).addClass('changed');

}

POSTED BY UZBEKJON AT 5: 28 AM 0 COM M ENTSLABELS: HOW TO, JAV ASCRIPT, T IP

POSTED BY UZBEKJON AT 11:40 PM 2 COM M ENTSLABELS: HOW TO, JQUERY, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 68/73

Page 69: JQuery HowTo

And now, use it like this:

$('.changePlease').myFunction();

And that is all there is :)

Coupure de page insérée par AutoPager. Page ( 21 ).

M O ND A Y, D E C E M B E R 2 2 , 2 0 0 8

Let Google host your jQuery library

Google hosts several JavaScript libraries such as Prototype, script.aculo.us,MooTools, Dojo, etc. It also hosts jQuery, as well as jQuery UI. The files arealready minimized, gzipped and if your visitors have already visited some sitethat loaded jQuery from Google Code then it already be on user's machine. Sothere is nothing to load.

UPDATE: Y ou can also use jQuery hosted by Microsoft CDNservers.

Anyway, so here is 2 ways of loading jQuery from Google Code:

<script src="http://www.google.com/jsapi">

</script>

<script type="text/javascript">

google.load("jquery", "1.2.6");

google.setOnLoadCallback(function() {

// Your code goes here.

});

</script>

I prefere loading it stright from the Google like this:

<script

src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min

.js"

type="text/javascript"></script>

Other links to jQuery files on Google:

http://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js

http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

Loading jQuery UI from Google CDN servers

Google CDN servers also host jQuery UI files. So if you are using jQuery UI youcan also load them using these links and code:

<script src="http://www.google.com/jsapi">

</script>

<script type="text/javascript">

google.load("jquery", "1.3.2");

google.load("jqueryui", "1.7.2");

google.setOnLoadCallback(function() {

// Your code goes here.

});

</script>

<!-- OR -->

<script

src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-u

i.min.js"

POSTED BY UZBEKJON AT 9: 55 PM 7 COM M ENTSLABELS: HOW TO, JQUERY, PLUGI N, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 69/73

Page 70: JQuery HowTo

type="text/javascript"></script>

Currently Google hosts these versions of jQuery UI library:

1.5.2, 1.5.3, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3, 1.8.0, 1.8.1,

1.8.2, 1.8.4

M O ND A Y, D E C E M B E R 1 5 , 2 0 0 8

How to create a jQuery plugin, extending jQuerythe easy way

I have read a great book on jQuery Learning JQuery . I skimmed through thechapter on extending jQuery and creating its plugins. It is quite easy. All youhave to do is to use this template:

(function($){

$.fn.extend({

myFunk: function() {

// You must return jQuery object

return $();

},

myPunk: function() {

return this.addClass('punked')

.bind('click', function(){

alert('You were punked!');

});

}

});

})(jQuery);

Then you can use your defined functions like this:

$('.select').myFunk();

$('.select').myPunk();

jQuery uses method chaining pattern so you need to return jQuery object fromyour newly created methods.

S UN D A Y, D E C E M B E R 1 4 , 2 0 0 8

How to bind events to AJAX loaded elements

We all use jQuery's AJAX helpers like $.get(), $.post() and $.load(). Wealso all use jQuery's event bindings. When you use them both, problems such asyour event bindings like click() are not bided to your new AJAX loadedelements. To solve this problem you need to bind events to your newly loadedelements.

NOTE: Make sure you don't bind the same event to the elements with this event alreadybound.

TIP: You should somehow separate newly created elements and then bind event incallback of an AJAX function.

Regarding the tip above. Here are two ways of separating AJAX loaded content:

1. You can load into some specific container <div id="ajax-loaded"></div> and then apply your events to the elements inside this container(Ex: $('#ajax-loaded .my-button').click(...)).

2. Add some class to your elements that are loaded on the server side.

You might also be interested in:

Cross domain AJAX queryingAJAX update content every X secondsDisplay loading GIF image while loading through AJAX

POSTED BY UZBEKJON AT 9: 43 PM 8 COM M ENTSLABELS: HOW TO, JQUERY, LINK, PERFO RM ANCE, REFERENCE, T IP

POSTED BY UZBEKJON AT 3: 19 AM 2 COM M ENTSLABELS: HOW TO, JQUERY, PLUGI N, REFERENCE, T IP

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 70/73

Page 71: JQuery HowTo

Update: Added a demo page that shows how to bind events toAJAX loaded elements here.

S A T UR D A Y, D E C E M B E R 1 3 , 2 0 0 8

How many elements were selected by jQuery

Recently I needed to find out how many elements were selected by jQuery.jQuery selector returns an array of elements jQuery object that has .length

attribute. So the easiest way is to get the length of returned jQuery object. Thesize of that object will be equal to the number of selected elements.

$('.someClass').length;

// Assume you have 4 .class elements

$('.class').length;

// would return 4

Also, you can use built in jQuery helper function called .size(). It returns thesame value as .length property but it is slightly slower, however the differenceis insanely small. So you can use .length or .size() depending on yourchoice.

// Example usage for .size()

$('.someClass').size();

Access to restricted URI denied" code: "1012

I was working on the interface for our catalogue/directory structure. We use greatJavaScript library jQuery as our JS framework. While working on page AJAXrequests to get child categories I came up to this error message / problem:

Access to restricted URI denied" code: "1012

xhr.open(type, s.url, s.async);

(This error was produced in Firebug, plug-in for Firefox)

The error occurs when my application tries to do an AJAX request call to localresource. In other words, 'Access to restricted URI denied" code: "1012' erroroccurs when javascript tries to load a file from my hard drive. The file type let itbe CSS, HTML, javascript does not matter.

Reason:

1. The reason for the error is Firefox's security model that does not allowretrieving/accessing localhost resources.

2. Also Firefox does not allow accessing resources from other domains(NOTE: www.example.com and example.com are considered two differentdomains as well).

Solution:

1. So, to solve this problem you need to deploy your files to your web serveror run one locally. You can run XAMPP or lightweight Denwer (similar toXAMPP, but it is in Russian).

2. To access resources from other domains you can put a simple proxyscript, as it is described in this “Cross domain AJAX scripting” post.

Coupure de page insérée par AutoPager. Page ( 22 ).

S A T UR D A Y, N O V E M B E R 1 , 2 0 0 8

POSTED BY UZBEKJON AT 1: 03 AM 7 COM M ENTSLABELS: AJAX , EV ENTS, HOW TO, JQ UERY, T IP , W ORKARO UND

POSTED BY UZBEKJON AT 1: 40 AM 2 COM M ENTSLABELS: ATTRIBUTES, BEGI NNER, HOW TO , I NSIG HTS, JQUERY, REFERENCE,SELECTORS, T IP

POSTED BY UZBEKJON AT 1: 17 AM 23 COM M ENTSLABELS: AJAX , ERROR, FIREBUG, JA V ASCRIPT, REFERENCE, W ORKA ROUND

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 71/73

Page 72: JQuery HowTo

Older Posts »

Set HTML tag’s / element’s attribute

In our previous post about “How to get an element’s / tag’s attribute” I describedhow to get element’s attribute. In this post I would like to show you how to setany HTML tag’s or element’s attributes. Don’t forget, jQuery can set anyattributes like id, class, style, name, title, etc.

Setting element’s attribute example:

// This code add title to all page links

$("a").attr("title", "This is a link");

// Set table cell's collspan attribute

$("td.myDoubleCell").attr("colspan", 2);

NOTE: You are not limited to W3 Consortium defined set of HTML attributes. So youcan also set your own attributes with their own values.

Here is an example:

//This code adds myAttr attribute with the value of 10

$("#container").attr("myAttr", "10");

You can use .attr("myAttr") to get the set attribute value. Cool ha?!

Getting HTML tag attribute of an element usingjQuery

Using jQuery you can get any attribute (ex: id, class, style, name, title, etc.)of any HTML tag (ex: <div>, <span>, <p>, etc.) using the.attr("attributeName") function. This method return a string of the element’sattribute.

Example:

Consider we have the following HTML tags on our page with correspondingattributes:

<div class="myContainer" id="wrapper">

Some content

<a id="siteLink" title="Google" href="">link</a>

</div>

And to get container's id attribute and the link's title attributes, we would usethe following jQuery code:

// Get the ID of the selected div

var divID = $("div.myContainer").attr("id");

// Get a title attribute of a link

var linkTitle = $("#siteLink").attr("title");

Here, divID would be equal to wrapper and linkTitle would be equal toGoogle.

NOTE: If your jQuery selection returns more than once element, .attr() function wouldreturn only the first element’s attribute.

Home

Subscribe to: Posts (Atom)

POSTED BY UZBEKJON AT 7: 31 AM 3 COM M ENTSLABELS: ATTRIBUTES, BEGI NNER, HOW TO , JQUERY, M ANIP ULATI ON

POSTED BY UZBEKJON AT 7: 11 AM 2 COM M ENTSLABELS: ATTRIBUTES, HO W TO, JQ UERY

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 72/73

Page 73: JQuery HowTo

jQuery is a javascript framew ork or javascript library that abstracts common javascript tasks and gives developerstools to get on w ith their lives. This blog - "jQuery How To" is a collection of jQuery How tos and resources related to

jQuery library.

© jQuery How to.

20/01/2011 JQuery HowTo

http://jquery-howto.blogspot.com/ 73/73