20/01/2011

JQuery HowTo

JQUERY HOWTO
B L O G I S A B O UT J Q UER Y J A V A S C R I P T L I B R A R Y. I C O L L EC T J A V A S C R I P T C O D E S N I P P ET S , H O W T O ' S , T I P S A ND P ER FO R M A NCE O B S ER V A T I O NS .

FRI DAY, OC TO B ER 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
}
P O S T ED B Y UZ B EK J O N A T 1: 23 P M 0 C O M M ENT S L A B ELS : B EG I NNER , J Q UER Y, P L UG I N, R EFER ENC E, T I P , T UT O R I A L

W ED NES D A Y, O C T O B ER 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 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.

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

1/73

20/01/2011
Let’s see how to do this. There are two way: 1. Redirect iPad visitors 2. Apply different CSS file for iPad users

JQuery HowTo

Most of the posts on the internet related to iPad user detection are suggesting and showing you how to redirect (including myself in my previous iPhone & iPod detection post). However, I would recommend the second option, applying different CSS file. You can apply the same technique described in applying different styling for javascript enabled browser with CSS post and apply different CSS rules for iPad visitors. Sidenote: If you decide to redirect iPad users rather than apply different CSS style rules, than I would recommend using server side detection and redirection. You can see an example PHP code by David Walsh.
P O S T ED B Y UZ B EK J O N A T 1: 15 P M 0 C O M M ENT S L A B ELS : CSS , HO W T O , J A V A S CR I P T , J Q UER Y, J Q UER Y M O B I L E, R EFER EN C E, T I P

T U ES D A Y, O C T O B ER 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 Microsoft contributed Globalization plugin or shortly jquery.glob.js . In this first post I will try to cover the very basics like library licensing, “the good & the bad” and some thoughts on how it could be improved (IMO).

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

So, there you go. One little improvement: "Don’t confuse, rename it!"
Before we talk about the jQuery globalization plugin license, let me mention that this plugin is now officially supported by jQuery Project. Which means that it will be under continues improvement by jQuery core team and will be compatible with the future jQuery and jQuery UI releases. Also globalization plugin will become a part of the jQuery UI project.

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

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

JavaScript library alternative to globalization plugin would be nice.
To be honest, JavaScript and jQuery community had a lack of localization libraries and jQuery Globalization plugin with over 350 localizations is a great solution. Surely, plugin’s exposed function names and namespacing could be improved, and most probably will be, but we’ll talk about it in our next “jQuery Globalization plugin tutorial” post. Stay tuned…
P O S T ED B Y UZ B EK J O N A T 3: 17 P M 0 C O M M ENT S L A B ELS : I NS I G HT S , JQ UER Y, J Q UER Y UI , NEW S , P LUG I N

S A T UR D A Y, S EP T EM B ER 2 5 , 2 0 1 0

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

2/73

20/01/2011

JQuery HowTo

Russian CDN for jQuery
I recently discovered that the biggest Russian search engine Yandex (yeah, it’s bigger than Google in Russia) is using jQuery on its home page. It also hosts all previous jQuery versions on it’s fast gzip enabled servers just like Google and MIcrosoft do. Because most of the Russian internet users have visited Yandex already, they already have it in their browser cache. I also did route tracing from Russian server to Google CDN servers and I was directed to the server in California, USA and pining the local Russian CDN server was at least 3 times faster. Anyway, if you decide to use Russian CDN to host your jQuery files here are the links:
Minified versions http://yandex.st/jquery/1.2.6/jquery.min.js http://yandex.st/jquery/1.3.0/jquery.min.js http://yandex.st/jquery/1.3.1/jquery.min.js http://yandex.st/jquery/1.3.2/jquery.min.js http://yandex.st/jquery/1.4.0/jquery.min.js http://yandex.st/jquery/1.4.1/jquery.min.js http://yandex.st/jquery/1.4.2/jquery.min.js

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

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

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

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

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

jQuery UI CSS files (matches original directory names) http://yandex.st/jquery-ui/1.8.0/themes/humanity/jquery.ui.all.mi n.css
P O S T ED B Y UZ B EK J O N A T 10: 19 A M 2 C O M M ENT S L A B ELS : JQ UER Y, L I NK , P ER FO R M A NC E, R ES O UR C E

FRI DAY, S EP TEM B ER 24, 2010

iPhone / iPod detection using jQuery & JavaScript
In this post you will learn how to detect iPhone/iPod using javascript/jQuery, redirect your iPhone users to mobile version of your site using javascript and alternative and better way to redirect your visitors using server-side PHP code snippet. The latest buzz around jQuery is upcoming jQuery mobile – support for mobile devices. Current jQuery core work fine on iPhone and iPod touch browsers and most of us have created a mobile version of our websites, developed or converted websites for others. Basically, jQuery is already being used on iPhone and iPod touch devices. Without any further ado…

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

3/73

20/01/2011
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) ); }

JQuery HowTo

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

Redirecting iPhone & iPod users
You may also use this script to redirect iPhone and iPod users to your website’s mobile version:
// Redirect iPhone/iPod visitors
function isiPhone(){ return ( (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) ); } if(isiPhone()){ window.location = "mob.example.com"; }

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

Redirect iPhone users using PHP
It is better to detect and redirect your iPhone users on the server-side. Here is a PHP code to redirect iPhone users:
// Redirect iPhone/iPod visitors
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod')){ header("Location: http://mob.example.com"); }

User agent strings for your reference:
/* User Agent String for iPhone Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/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 not like to be redirected to mobile versions of your websites. That’s why your mobile version should always include a link to your non-mobile website. The above scripts can be rewrote to check if user has chosen not to be redirected. Either set cookie or a URL parameter.
P O S T ED B Y UZ B EK J O N A T 10: 36 A M 0 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, J Q UER Y M O B I L E, R EFER ENC E, T I P

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

2

).

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

4/73

20/01/2011
W ED NES D A Y, S EP T EM B ER 2 2 , 2 0 1 0

JQuery HowTo

jQuery mobile source code
If you want to download jQuery Mobile source code and look into it just like everybody else, we are all out of luck :( As I mentioned in my previous post jQuery mobile facts, the source code will be available in October this year. The jQuery Mobile source will not be in a separate jquery.mobile.js file. It will be right in the jQuery core. This means that jQuery team is fixing and improving jQuery core so that it works nicely in all major mobile phones and devices. By the way, if you want to keep track of the jQuery mobile source code and be the first one to download it, when it is available, you should watch jQuery on GitHub. The big part of the upcoming jQuery mobile is new UI components that work and render nicely in all mobile devices and degrade gracefully. So, keep an eye on jQuery UI as well. Here is the jQuery UI GitHub page. Meanwhile you can read all jQuery mobile facts here.
P O S T ED B Y UZ B EK J O N A T 10: 30 A M 0 C O M M ENT S L A B ELS : I NS I G HT S , JQ UER Y, J Q UER Y M O B I L E, J Q UER Y UI , NEW S

T U ES D A Y, S EP T EM B ER 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 Cookie plugin, it’s improved version with more functions and of course easy to read and short examples on how to use these functions. I will try to keep this post short and will not explain what cookies are and how to eat them. There are plenty of articles covering it already. Here are javascript functions by Peter-Paul Koch to getCookie() , setCookie() and deleteCookie() :
function setCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }

function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.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 javascript to create, edit and delete your cookies:
// Create/write a cookie and store it for 1 day

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

5/73

20/01/2011
setCookie('myCookie', 'myValue', 1);

JQuery HowTo

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

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

These 3 javascript functions are all you need to manage your cookies, but if you want to do it in “jQuery style” than you can use jQuery Cookie plugin or it’s improved version. Here is how to use jQuery Cookie plugin in your code:
// Setting a cookie $.cookie('myCookie':'myValue');

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

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

// Delete a cookie $.cookie('myCookie', null);

With an improved version of the plugin you can set and get multiple cookies in one call. The improved version of the jQuery Cookie pluin only adds few additional bytes. So it really worth it.
// Set multiple cookies $.cookie({ 'cookie1':'value1', 'cookie2':'value2' });
P O S T ED B Y UZ B EK J O N A T 3: 04 P M 0 C O M M ENT S L A B ELS : B EG I NNER , J A V A SCR I P T , J Q UER Y, P LUG I N

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 on all major mobile browsers. In this post I will try to lay down all the facts that I could find about jQuery Mobile, so that you are up to date. jQuery team has mentioned that they were planning and started to work on jQuery for Mobile devices when they announced jQuery 1.4. John Resig said that they already had different mobile devices from sponsor for testing purposes. Anyway, jQuery Mobile is officially announced now, but there is a very little information about it. Here are some facts that I found: 1. jQuery Mobile will be in core, NOT as a separate distribution like
jquery.mobile.js

2. jQuery UI team will improve current jQuery UI and develop new mobile components (initial designs). 3. Release of the jQuery Mobile and new jQuery UI components is planned for October 2010. 4. As of writing of this post, jQuery Mobile source code is not available. The code will be pushed to the jQuery core’s GitHub repository and announced on the official jQuery mobile page. 5. You can help jQuery Mobile project by testing jQuery core on your mobile devices at TestSwarm. That’s all I could find on jQuery Mobile for now. Subscribe to my RSS or follow me on Twitter to stay updated about news related to jQuery Mobile.
P O S T ED B Y UZ B EK J O N A T 9: 38 A M 0 C O M M ENT S L A B ELS : JQ UER Y M O B I LE, L I NK , NEW S

W ED NES D A Y, A U G U S T 1 1 , 2 0 1 0

jQuery.live() – event binding to AJAX loaded
http://jquery-howto.blogspot.com/ 6/73

20/01/2011

JQuery HowTo

elements
jQuery.live() function was introduced in jQuery version 1.3. It makes it easy

to dynamically bind events to DOM elements that have not yet been created. In other words, it helps you to easily attach events to AJAX loaded elements that match your criteria. NOTE:

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

So, how does .live() function works?
It uses event delegation technique to bind to the events that fire on your page. In other words, it binds an event to the DOM tree’s root and listens to all events. When an event is fired it checks it’s originator and checks if we have bound any events to that particular DOM element.
// Example usage of jQuery().live() function $('.mySelector').live('click', function(event){ // my click event handler });

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

You can also pass in additional data to your events to overcome some issues caused by closure. This was introduced in jQuery 1.4. Also, it worth mentioning that data is passed when the binding is made. Keep this in mind when you pass in dynamic data.
$('.mySelector').live('click', {myVar: 'myVal'}, function(event){ // my click event handler });

NOTE:

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

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

jQuery.live() function performance
Because .live() uses event delegation and performs additional checks, it will always be slower then events attached to the DOM elements using .bind() function (this includes shorthands like: .click() , .submit() , etc.). However, you can improve your .live() function performance providing context (as of ver. 1.4).
// Using context for better performance // Note that context is a DOM element, not jQuery $('.mySelector', $('.myParent')[0]).live('click', function(event) { // my faster click event });

Unbinding events attached using .live() function
.unbind() function equivalent of .live() function is .die() . You can unbind

ALL events attached using .live() function from an element by simply calling
.die() . If you want to remove a specific event or a specific handler function of a

specific event type, you can call .die('event', functionHandler) .

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

7/73

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

JQuery HowTo

// 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.
P O S T ED B Y UZ B EK J O N A T 10: 33 A M 0 C O M M ENT S L A B ELS : A JA X , B EG I NN ER , EV ENT S , J Q UER Y, P ER FO R M A NC E, R EFER ENC E

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 the page. Unlike checking loaded jQuery version ( $().jquery ), checking jQuery UI version is a bit different. Checking currently loaded jQuery UI version on the page:
// Returns jQuery UI version (ex: 1.8.2 ) or undefined $.ui.version

// Alternatively jQuery.ui.version

You would most probably use it in the if statement:
if($.ui.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 }
P O S T ED B Y UZ B EK J O N A T 12: 10 A M 2 C O M M ENT S L A B ELS : B EG I NNER , HO W T O , JQ UER Y UI , T I P

Coupure de page insérée par AutoPager. Page (
M O ND A Y, A P R I L 1 9 , 2 0 1 0

3

).

jQuery YouTube plugin demo
Long overdue demo for my jQuery YouTube plugin – jYouTube is now available here. The plugin can fetch and get you any YouTube video’s screenshot or thumbnail by its URL or video id. Here is an example:
// Getting video screenshot by YouTube video ID $.jYoutube('rSUfWXcNAOw');

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

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

See the plugin in actio n on jQuery Y ouTube demo page.

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

8/73

20/01/2011
I hope you will find the plugin useful.
P O S T ED B Y UZ B EK J O N A T 5: 51 A M L A B ELS : JQ UER Y, P L UG I N 1 C O M M ENT S

JQuery HowTo

S UN D A Y, F EB 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 while since I updated the plugin, so I downloaded the latest version and while looking thought the code found couple of bugs. So, here comes updated and fixed jQuery Tweeter plugin - jTwitter 1.1.1. In this release, I fixed a little bug that would not allow you request Tweets without number of posts like this:
// Defaults to 5 latest posts $.jTwitter('jQueryHowto', function(posts){ //Callback function with the user data });

You can specify the number of posts you want to be fetched like so:
// Get latest 13 posts $.jTwitter('jQueryHowto', 13, function(posts){ //Callback function with the user data });

Also, I created a simple demo page for the plugin here. Please visit and see the code and also note that with this plugin you can create a custom Twitter badge with no design limitations! Update: Pushed the project to GitHub.
P O S T ED B Y UZ B EK J O N A T 6: 10 A M 0 C O M M ENT S L A B ELS : JQ UER Y, L I NK , NEW S , P LUG I N

T H UR S D A Y, F EB 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 so easy, we all create our own jQuery plugins. And all of us have our own code syntax preferences. For example:
function myFunction() { ... }

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

If you want to publish your jQuery plugins following jQuery core code writing guidelines is a good idea. This would make your code more easier to read to other jQuery developers. Follow the link above and go through the guidelines (it will only take a few minutes). The guidelines page shows gives you general guidelines, but I went through the jQuery core code and found several additional ones. I lay they out at the end of this post. In short, the official guidelines are as follows: (Taken from official docs) 1. Use tabs to indent your code 2. Use liberal spacing":
function myFunction ( myVar, myVar2 ) { // Pay attention to spaces around // the brackets and curly brackets }

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

9/73

20/01/2011
3. Use strict equality checks whenever possible (===)

JQuery HowTo

4. Braces should always be used on blocks and statements should not be on the same line as a conditionals:
// NO: if ( true ) blah();

// YES: if ( true ) { blah(); }

5. When checking an object type:
String: typeof object === "string" Number: typeof object === "number" Function: jQuery.isFunction(object) Array: jQuery.isArray(object) Element: object.nodeType

See full list on official docs page (link above)

6. Don't use "string".match() for RegExp, instead use .test() or
.exec()

7. Node related rules:
.nodeName should always be used in favor of .tagName . .nodeType should be used to determine the classification of a

node (not .nodeName ). Only attach data using .data(). Now let’s see other additional rules that I could spot reading the jQuery core code. Additional jQuery code / syntax guidelines: 1. The first thing that I noticed was multiline comments did not use common
/* comment */ syntax. In jQuery core all multiline comments use line

comment syntax // comment .
// This is an example of multiline // comment syntax used in jQuery core.

2. Local variables are declared and initialized on one line just below the function declaration with no extra line:
function someFunction () { var target = arguments[0] || {}, i = 1, name;

// Empty line and then the rest of the code }

3. When declaring objects, there is no space between property name and colon:
{ myName: "", myFunc: function( ) {} }

4. All strings are in double quotes " " , not single quotes ' ' :
var myMarkup = "<a href='/a'>a</a>";

5. The last but not least, variable naming uses camelCase.
P O S T ED B Y UZ B EK J O N A T 12: 06 P M 2 C O M M ENT S L A B ELS : B EG I NNER , I NSI G HT S , J Q UER Y, R EFER ENC E, T I P

S A T UR D A Y, F EB 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 your HTML document’s DOM using jQuery and/or JavaScript. It also gives you an example code. This post is not extensive explanation of how to manage and work

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

10/73

20/01/2011
create iframes using jQuery and JavaScript and serves as a note.

JQuery HowTo

with iframes using jQuery. This post simply shows you how to dynamically

Creating iframe is similar to creating any DOM element. All you need to do is to use jQuery factory like this:
// Create an iframe element $(‘<iframe />’);

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

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

Don’t forget that the iframe source is just an iframe’s attribute. So you can set that just like any other attribute.
// Setting iframe's source $('<iframe />').attr('src', 'http://www.google.com');

UPDATE: As BinaryKitten point’s out below, with jQuery 1.4 you can do it using the following syntax:
// Set attributes as a second parameter $('<iframe />', { name: 'myFrame', id: ... }).appendTo('body');
P O S T ED B Y UZ B EK J O N A T 10: 19 A M 6 C O M M ENT S L A B ELS : B EG I NNER , D O M , HO W T O , HT M L , M A NI P UL A T I O N, R EFER EN C E

'myFrame',

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 version 1.4! Today is jQuery’s birthday and what can be a better present than a new version release? As I tweeted previously jQuery 1.4 has a lot to offer: better
iframe support, flexible events (this in particular), etc. If you have not been

keeping up to date with jQuery 1.4 features John Resig will announce 1.4 release details 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 might find the following resources useful: 1. 14 Days of jQuery 2. Official jQuery Blog 3. jQuery 1.4 Cheatsheet 4. jQuery on Tweeter If you have any more resources related to jQuery 1.4 please share in comments. Happy Birthday jQuery and jQueriers :)
P O S T ED B Y UZ B EK J O N A T 6: 49 A M 5 C O M M ENT S L A B ELS : JQ UER Y, L I NK , NEW S , R ES O UR C E

Coupure de page insérée par AutoPager. Page (
FR I DA Y, NO V EM B ER 6, 2009

4

).

Cross-domain RSS to JSON converter [jQuery plugin]
No doubt that Web2.0 is one of the best things that happened in our lifetime

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

11/73

20/01/2011

JQuery HowTo

(besides the internet itself). When we mention Web2.0 first things that come into our minds are AJAX, rounded corners, clean and light layouts and of course RSS feeds. Nowadays, you either provide an RSS feed or consume it in your web app using AJAX/JavaScript. The only bad thing is that you can not request cross-site content with AJAX requests. Requesting someone else’s RSS in your JavaScript falls into this limitations. One way to overcome this problem is to apply a server-side proxy workaround. However, there is even better solution and workaround – RSS to JSON conversion. Basically, using Google Feeds API service and jQuery plugin you can request and get any RSS from different domain converted into the JSON object in your javascript. 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 to include jquery.js and Google Feeds API plugin jquery.jgfeed.js . Then use jQuery 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 it wants with it. Great workaround isn’t it :) To see jGFeed() ’s argument lists and how to use it please read this post.
P O S T ED B Y UZ B EK J O N A T 8: 13 A M 9 C O M M ENT S L A B ELS : A JA X , HO W T O , J Q UER Y, JS O N, P L UG I N, T I P , T O O L S, W O R K A R O UND

T U ES D A Y, NO V EM B ER 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 not use a callback functions. They usually simply work on DOM elements or do some calculations. But there are cases when we need to define our own custom callback functions for our plugins. And this is especially true when our 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

}); } });

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

12/73

20/01/2011

JQuery HowTo

What is bad in this jQuery code is that the callback function is defined and hardcoded right in the plugin itself. The plugin is not really flexible and its user will have to change the plugin code, which is bad! So the solution is to define your own custom callback function argument. Here is how 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 if you want to create a simple callback function for your jQuery plugin, for example the one that executes on your own custom events. To achive this you can 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' });
P O S T ED B Y UZ B EK J O N A T 7: 54 A M 5 C O M M ENT S L A B ELS : A JA X , B EG I NN ER , EV ENT S , HO W T O , I NSI G HT S , J Q UER Y, P L UG I N, R EFER ENC E, T UT O R I A L, W O R K A R O UND

S UN D A Y, NO V EM 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 data about 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 to your 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 only Twitter user details but also any number of that user’s latest posts. And yes, all these you can do without any Twitter API keys. Here is the main function and its argument details:
$.jTwitter(username, numberOfPosts, callbackFunction);

/* username - Twitter username

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

13/73

20/01/2011
numberOfPosts - Number of user posts to get callbackFunction - callback function to call when data is loaded */

JQuery HowTo

Let’s see a real life example now. In example below, we are fetching latest 3 posts of jQueryHowto Twitter user and appending those post messages to some DOM 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 function here 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

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

14/73

20/01/2011
ootSuite</a>', 'created_at':'Thu Sep 17 17:20:21 +0000 2009', 'truncated':false, 'user':{ 'profile_sidebar_fill_color':'e0ff92',

JQuery HowTo

'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)',

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

15/73

20/01/2011
'utc_offset':-21600, 'followers_count':2035,

JQuery HowTo

'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 information about 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.
P O S T ED B Y UZ B EK J O N A T 11: 08 P M 9 C O M M ENT S L A B ELS : A JA X , J Q UER Y, J S O N, NEW S, P L UG I N, R EFER ENC E

T U ES D A Y, O C T O B ER 2 0 , 2 0 0 9

JavaScript / jQuery password generator
This month, October, is a National Cyber Security Awareness Month. The aim is to increase cyber and internet security awareness among surfers. Google and others are joining the move. So I thought I would write a post regarding internet security to add my 2 cents. In this post you will find JavaScript function that generates 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 and optional boolean value true if you want to include special characters in your generated passwords.

Examples of generated passwords
password(8); // Outputs: Yrc7TxX3

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

16/73

20/01/2011
password(12, true); //Outputs: C}4_ege!P&#M

JQuery HowTo

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);
P O S T ED B Y UZ B EK J O N A T 6: 37 A M 2 C O M M ENT S L A B ELS : JA V A S CR I P T , JQ UER Y, S EC UR I T Y, T O O LS

T H UR S D A Y, S EP T EM B ER 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 in Visual Studio, hosting jQuery on Microsoft CDN servers is actually a logical and good 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 own jQuery hosted servers, bu to share links to Microsoft hosted jQuery library. Here we 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 add more releases in the future. To see a full list of the JavaScript libraries and their URLs that are already hosted on CDN cache go here: www.asp.net/ajax/cdn
P O S T ED B Y UZ B EK J O N A T 11: 05 P M 2 C O M M ENT S L A B ELS : A JA X , J A V A S CR I P T , J Q UER Y, L I NK , NEW S, P ER FO R M A NC E

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

17/73

20/01/2011
Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, S EP T EM B ER 1 6 , 2 0 0 9

JQuery HowTo
5 ).

Get URL parameters & values with jQuery
In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient. Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by 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 an extension 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 URL parameter values in the following way:

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

18/73

20/01/2011
// Get object of URL parameters var allVars = $.getUrlVars();

JQuery HowTo

// Getting URL var by its nam var byName = $.getUrlVar('name');

That’s it! You might also find the following jQuery related articles on this blogs interesting: 1. Cross-domain AJAX querying with jQuery 2. Javascript for() loop vs jQuery .each() performance comparison 3. Create jQuery custom selectors with parameters 4. JavaScript / jQuery password generator
P O S T ED B Y UZ B EK J O N A T 12: 59 A M 13 C O M M ENT S L A B ELS : B EG I NNER , HO W T O , HT M L , J A V A S C R I P T , JQ UER Y, T I P , W O R K A R O UND

T U ES 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 are popular in Japan and they are mainly used there to quickly get to some website on their mobiles by simply taking a picture of the QR code. You may read more about 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 open this website. Cool ha?! Anyway, there are plenty of free online QR code generator sites, but no JavaScript and jQuery plugins/functions. So, I quickly searched for a free online QR code generator sites with “friendly” URL’s and put together a javascript and jQuery functions that generate QR barcode image’s URL for passed URLs. I used Kaywa & University of Bath services.

See jQuery and QR code in action o n 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

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

19/73

20/01/2011
between 1 and 40 and the generated image will 32 x your argument. Here is javascript and jQuery code for University of Bath barcode generator:
// JavaScript function function qrcode(url){ return 'http://go.bath.ac.uk/qr/download?DATA='+url; } qrcode('http://jquery-howto.blogspot.com');

JQuery HowTo

image site as the second argument to the function. The size argument mut be

// 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...
P O S T ED B Y UZ B EK J O N A T 2: 43 A M 5 C O M M ENT S L A B ELS : JA V A S CR I P T , JQ UER Y, P L UG I N, R ESO UR C E, T O O L S

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

Can't set / change CSS background image with jQuery problem solution
Hello everyone. I’ve been busy lately with some projects and could not write much on “jQuery HowTo” blog. So, when I came across this little problem, I thought I would share it with you. Anyway, I was working on one of my projects and I needed to set a background image using jQuery on some div . At first my background setting code looked like 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 why background images were not being set by jQuery. Anyway, after 10-20 minutes I realized that jQuery sets CSS properties as key : value and in our case valued had to be in url(image.jpg) form. Solution to “background images are not being set” problem is to set them like this:
$('#myDiv').css('background-image', 'url(my_image.jpg)'); // OR $('#myDiv').css('background', 'url(path/to/image.jpg)');
P O S T ED B Y UZ B EK J O N A T 12: 36 A M 9 C O M M ENT S L A B ELS : A T T R I B UT ES , B EG I NNER , C S S , ER R O R , J Q UER Y, T I P

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

jQuery.noConflict – Resolving conflicts with other javascript 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 simple button hide to full blown galleries. Plugins let non developers easily add functionality they need to their websites and there are times when one might include more than one javascript library such as prototype.js, YUI or mootools with jQuery. They all use $ as their main function name. Including second library might brake the behavior of the first one. To resolve such cases jQuery introduces .noConflict() method. When you call .noConflict() jQuery will return $() to it’s previous owner and

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

20/73

20/01/2011
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>

JQuery HowTo

You can also use the following code snippets to still use $() in your code, but with 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 use it as your shorthand: var $_ = jQuery;
P O S T ED B Y UZ B EK J O N A T 7: 42 A M 5 C O M M ENT S L A B ELS : B EG I NNER , HO W T O , I NS I G HT S , JQ UER Y, R EFER ENC E, T UT O R I A L , W O R K A R O UND

W ED NES 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 the mouse was on the page. Tracking mouse position on the page with jQuery is easy. You don’t need to check what browser the script is running like it is used to be with plain JavaScript. To identify where the mouse is in jQuery all you have to 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 current document and triggered every time mouse moves. The coordinates are calculated in 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 document root, by subtracting element’s position from document root you get mouse positions relative to that element. Long story short here is the code to do just that:
$("#someDiv").click(function(e){ var relativeX = e.pageX - this.offsetLeft; var relativeY = e.pageY - this.offsetTop; });

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

21/73

20/01/2011

JQuery HowTo

Don’t forget that you can bind any mouse event to any element and then get mouse positions. You can easily create a draggable object with click and
mousemove 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. As always, you don’t need to worry about cross browser compatibility issues while using jQuery. To learn more see more examples here.
P O S T ED B Y UZ B EK J O N A T 11: 20 P M 4 C O M M ENT S L A B ELS : A T T R I B UT ES , B EG I NNER , EV ENT S , HO W T O , JQ UER Y, R EFER ENC E, T UT O R I A L

Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, J UN E 2 4 , 2 0 0 9

6

).

jQuery custom selectors with parameters
My last tutorial on how to create a custom jQuery selector showed you the basics of creating custom filters in jQuery. Now, it is time to get more serious with selectors and create more advanced jQuery selectors – custom jQuery selectors 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 basic syntax 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 an

information about our selector. Here is what it looks like:
$('a:test(argument)'); //meta would carry the following info: [ ':test(argument)', // full selector 'test', '', 'argument' ] // only selector // quotes used // parameters

$('a:test("arg1, arg2")'); //meta would carry the following info: [ ':test('arg1, arg2')', // full selector 'test', '"', 'arg1, arg2' ] // only selector // quotes used // parameters

Here as you can see, we can make use of the arrays fourth (meta[3] ) value to get 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 non empty rel attribute and make it select any element with specified non empty attribute. Here is the code to do just that:
$.expr[':'].withAttr = function(obj, index, meta, stack){ return ($(obj).attr(meta[3]) != ''); };

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

22/73

20/01/2011
See it in action here.
P O S T ED B Y UZ B EK J O N A T 6: 42 A M 3 C O M M ENT S L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, R EFER ENC E, SEL EC T O R S , T I P , T UT O R I A L

JQuery HowTo

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 of the most used jQuery tutorials. By selecting all anchor links on the page and for example adding a CSS class with only one jQuery line shows how jQuery is simple and powerful. Also if you are progressively enhancing your website this is one of the trick you might use. Actually, I had to select all external links and add an image that indicates it the other day. So, I created a custom jQuery selector called :external that makes finding external links easier for you. (Read “Custom jQuery Selectors” post to learn 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 links Dynamically add an image after the link to indicate that it is an external link Bind a click event to track what links where clicked etc. Update: The return part was update to take into the account the mailto links as suggested in comments by Phillipp and Karl below.
P O S T ED B Y UZ B EK J O N A T 1: 57 A M 5 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, P L UG I N, R EFER ENC E, S EL EC T O R S , T I P , T UT O R I A L

W ED NES 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 is undoubtedly one of the jQuery features that makes it a great javascript library. On top of standard CSS selectors jQuery introduces some custom selectors that 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 custom selectors 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:

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

23/73

20/01/2011
$('.someClasses:test').doSomething();

JQuery HowTo

Let’s now create a very simple custom selector using the template above. Let’s say we want a custom jQuery selector that will return elements with nonempty
rel 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 not empty 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.
P O S T ED B Y UZ B EK J O N A T 3: 43 A M 13 C O M M ENT S L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, P L UG I N , R EFER ENC E, T UT O R I A L

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 create Firefox plugins using web programming languages like HTML, CSS and JavaScript. 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 not available in Firefox yet. The good news is that Jetpack is using jQuery and you can use it to do all kinds of stuff like responding to user click events, manipulate any website DOM elements and use cross-site XMLHttpRequest object, etc. Besides, Jetpack can be setted up to use other javascript libraries such as prototype.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 this links: 1. Watch this Jetpack video Good starting point to get an idea of what Jetpack is and how jQuery is used within it. Also good starting point to understand what kind of things can be don with Jetpack. 2. Read Jetpack tutorial Official Jetpack introduction tutorial from Jetpack team. Probably the first article you must read about developing for Jetpack. 3. Jetpack API documentation A list of global variables that are available in your Jetpacks. Currently it has 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 by investigating someone else’s code easier. I am planning to post more Jetpack tutorials on this blog and try to show what kind of things can be done using Jetpack and jQuery. Keep tuned by following me on Twitter (@jQueryHowto) or subscribe to blog’s RSS.
P O S T ED B Y UZ B EK J O N A T 4: 04 A M 1 C O M M ENT S L A B ELS : I NS I G HT S , JQ UER Y, L I NK , N EW S , P LUG I N, R EFER ENC E, R ES O UR C E

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

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

24/73

20/01/2011
tutorials on the blog.
See a list o f all jQuery beginner tutorials o n this blog.

JQuery HowTo

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 developers who are landing on this blog through search are jQuery Beginners and looking for basic jQuery method explanations. So publishing more beginner tutorials would benefit them. They would get more relevant information 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 online discussion boards lately answering and helping developers with their jQuery problems. The jQuery community on twitter is quite active and most of the jQuery problems I came across were jQuery beginners questions. I could not squeeze my ideas or explanations of jQuery basics in 140 characters, so I had to search the web for explanation and post a link to the website. Message to non beginner readers: I hope I will not lose intermediate and advanced jQuery developers with this posts. I enjoy your insights and comments on my posts and actually learn a lot more from your feedback. I will try to post no more than one beginner tutorial or insight 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 on this blog with backdate. I will try to keep this post updated with the links for my beginner posts so you can bookmark this page or share it with your jQuery beginner colleagues. See all jQuery beginner tutorials o n this blog.

1. Using $.noConflict() 2. How to check if checkbox is checked 3. Identify how many elements were selected 4. Adding custom functions to jQuery 5. Identifying & locating mouse position in jQuery 6. How to load jQuery from Google CDN servers 7. Setting HTML tag’s attribute in jQuery 8. Getting HTML tag’s attribute in jQuery 9. Binding jQuery events to AJAX loaded elements 10. How to disable and enable an element 11. Quick tip to solve a problem with setting CSS background image to an element
P O S T ED B Y UZ B EK J O N A T 6: 38 A M 1 C O M M ENT S L A B ELS : B EG I NNER , N EW S , T UT O R I A L

Coupure de page insérée par AutoPager. Page (
T U ES D A Y, J UNE 2 , 2 0 0 9

7

).

Javascript for() loop vs jQuery .each() performance comparison
This post is an outcome of 15 minutes of free time and a question that I had yesterday. 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 will get 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

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

25/73

20/01/2011
jQuery’s .each() iterator. All I did was just an iteration and no array

JQuery HowTo

amendments or any other logic. I know it is very basic, but that’s exactly what I want 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 ========== 10,000 100,000 1,000,000

Time ====== 7ms 62ms 613ms

jQuery .each() loop

Array size ========== 10,000 100,000 1,000,000

Time ====== 10ms 177ms 1100ms

As you can see native for loop is never over 1ms. That’s probably because we are not doing anything with our array and browser simply optimizes the code or maybe its that fast :) Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.
P O S T ED B Y UZ B EK J O N A T 7: 08 A M 10 C O M M ENT S L A B ELS : I NS I G HT S , JA V A S CR I P T , J Q UER Y, P ER FO R M A NC E, R EFER ENC E, T ES T , T I P

FRI DAY, M AY 29, 2009

Tip for jQuery & handheld device developers
This week’s usual “Friday short post” about using jQuery in handheld devices. If you are a developer who is using jQuery in applications that were developed for use in environments with small processing power such as handheld devices, mobile phones, PDA’s, etc. you will find this post useful. Anyway, back to the topic. For whatever reasons you chose to use jQuery in your application (I would suggest using plain javascript for better performance) jQuery effects such as animation, hide and show, etc. most likely were probably one of the reasons. Unfortunately, jQuery effects are process intensive and in “slow” environments it is recommended to turn them off. Fortunately, jQuery provides you with such a method. It lets you disable all animations and effects by changing jQuery.fx.off setting to true .
// Dissable all effects jQuery.fx.off = true;

// Shorthand $.fx.off = true;

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

26/73

20/01/2011

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 (by changing CSS rules display:none; display:block; ) to save CPU processing time. NOTE:

By setting the jQuery.fx.off back to false you enable all animations and effects.
P O S T ED B Y UZ B EK J O N A T 6: 48 A M 3 C O M M ENT S L A B ELS : A NI M A T I O N, HO W T O , I NS I G HT S, J Q UER Y, P ER FO R M A NC E, R EFER ENC E, T I P

W ED NES 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 layer that makes Google feed API easier to use for jQuery developers. The advantage of using this lightweight jQuery plugin is that you don’t have to learn and go through new API documentation. Do wnload Go ogle Feed A PI 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 load callback – callback function to call after RSS feed is loaded num (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 the following 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" ]

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

27/73

20/01/2011
}, { "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" ] }, ... }

JQuery HowTo

If you don’t specify a URL it will also return false. If you want to use your own Google Feed API key you can get one here.
P O S T ED B Y UZ B EK J O N A T 9: 45 A M 9 C O M M ENT S L A B ELS : A JA X , J Q UER Y, J S O N, P L UG I N

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 using Digg this (diggthis.js) button code with jQuery’s .wrap() method. According to him Mozilla Firefox (FF) is freezing and Apple Safari is crushing when he tries to wrap 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 remove the div that contains the script (.rounded ), then create a new <div> and then insert the removed div (.rounded ) back into the newly created div like this:
$(document).ready(function(){ $("div.rounded").remove().wrap('<div></div>').appendTo("#some where"); });
P O S T ED B Y UZ B EK J O N A T 7: 07 A M 0 C O M M ENT S L A B ELS : DO M , ER R O R , J Q UER Y, M A NI P UL A T I O N, T I P , W O R K A R O UND

FRI DAY, M AY 22, 2009

Remove n’th table column - jQuery plugin
My usual short Friday post. Today I would like to share with you a new utility I wrote to work with HTML tables. We already have jQuery functions to add table row, remove table row (on user click), add table row number plugin and now here is jQuery code to remove table column.

jQuery utility to remove table’s n’th column:
$.fn.removeCol = function(col){ // Make sure col has value

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

28/73

20/01/2011
if(!col){ col = 1; }

JQuery HowTo

$('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 that column. If you don’t supply any column number it removes the first table column by default.
P O S T ED B Y UZ B EK J O N A T 6: 01 A M 7 C O M M ENT S L A B ELS : HO W T O , HT M L, J Q UER Y, M A NI P UL A T I O N, P L UG I N, R EFER ENC E

Coupure de page insérée par AutoPager. Page (
T H UR S D A Y, M A Y 2 1 , 2 0 0 9

8

).

Remove table row on user click
This post is about removing a table row on user click. I needed this functionality for a project of mine. Online application had a table with data that user can dynamically add and remove. With progressive enhancement I also need to add a functionality to one of the tables that enables users to delete table rows when that 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 to any 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 table row 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 your database table. In my case I had to set up a server side code to do that. With one extra AJAX call to my server side script the functionality was ready.

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

29/73

20/01/2011
$('table td').click(function(){ $.get('deleteRow.php', {id: $(this).parent().attr('id')}, function(){ $(this).parent().remove(); }); });

JQuery HowTo

In the jQuery code above, instead of removing table row straight away we are making an AJAX call to our server side code that also removes that row from our database and then on AJAX call completion we removing table row.
P O S T ED B Y UZ B EK J O N A T 12: 35 A M 3 C O M M ENT S L A B ELS : HO W T O , HT M L, J Q UER Y, M A NI P UL A T I O N

FRI DAY, M AY 15, 2009

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. So this Friday I will give you a small jQuery utility function that will give you a way to get any YouTube video’s still image or in other words any YouTube video’s thumbnail. All you need to know is that YouTube video’s URL address or at least video’s YouTube ID. Couple of months ago I wrote a javascript function that does just that, gets YouTube video’s thumbnail. Today, I am rewriting that code as a jQuery utility function and releasing it as jQuery plugin called jYouTube. Do wnload jQuery Y outube plugin - jY o uTube

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 screenshot URL. 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 actio n 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).

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

30/73

20/01/2011
P O S T ED B Y UZ B EK J O N A T 8: 43 A M 1 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, P L UG I N, T O O L S

JQuery HowTo

T U ES 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 this post I will show you how to replace one image with another one in specific time intervals. For example: replacing image1.jpg with image2.jpg every 5 seconds. In javascript, whenever one says “every X seconds” or “time intervals” s/he is talking 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 elegant way 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 on one 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 fade in 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 interval we 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 can easily 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>

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

31/73

20/01/2011
<script> function swapImages(){ var $active = $('#myGallery .active');

JQuery HowTo

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.
P O S T ED B Y UZ B EK J O N A T 4: 42 A M 12 C O M M ENT S L A B ELS : A NI M A T I O N, CS S, HO W T O , HT M L , J Q UER Y, T UT O R I A L

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 is one of most occurred problems in web development. Rather than dealing with this problem server side, eating up your CPU process time, it is much easier and better to deal with this problem client side using JavaScript. When we talk javascript, 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 or preventing 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'); });

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

32/73

20/01/2011

JQuery HowTo

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

Bonus: disable submit button on form submission for all forms 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 “Disabling and enabling elements in jQuery” (very short) post.
P O S T ED B Y UZ B EK J O N A T 11: 45 P M 5 C O M M ENT S L A B ELS : A T T R I B UT ES , EV ENT S , HO W T O , HT M L, T I P , T UT O R I A L , W O R K A R O UND

FRI DAY, M AY 1, 2009

Remove the bottom table row using jQuery
I have posted a small jQuery code a while ago which adds a table row at the bottom of any given table. The code takes into the consideration tbody tag and also can be used as a jQuery plugin. Recently I was asked to write a jQuery or JavaScript code that removes the last/bottom row from the given table. The jQuery code I wrote was surprisingly small.

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 the consideration the possible <tbody> and <tfoot> HTML tags that can be found in tables.
// 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 can amend the code to make it remove n’th row).

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

33/73

20/01/2011
/* 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(); } }); }

JQuery HowTo

// 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.
P O S T ED B Y UZ B EK J O N A T 7: 57 A M 2 C O M M ENT S L A B ELS : DO M , HO W T O , HT M L , JA V A S C R I P T , JQ UER Y, M A NI P UL A T I O N, P L UG I N, T I P , T UT O R I A L

Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, A P R I L 2 9 , 2 0 0 9

9

).

jQuery Twitter API plugin
UPDA TE: Plugin has been updated! For more up to date information read this post.

You might have noticed that I am talking and spending more time on Twitter lately. I have been helping Twitter users with their jQuery related questions and problems as well. If you are using Twitter and have some kind of jQuery related question I will be happy to help. Anyway, after I found a Twitter JSON(P) API url last week, I spent some time playing with it and ended up with a jQuery plugin that when given a Twitter username retrieves and returns javascript object with user detials such as followers & following counts, full name, homepage URL, etc. Do wnload jQuery Tw itter A PI - jTw itter here. Update: No w 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",

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

34/73

20/01/2011
"profile_background_tile":false, "profile_sidebar_border_color":"87bc44", "profile_background_color":"9ae4e8", "profile_text_color":"000000"

JQuery HowTo

"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 URL as well. Using this jQuery plugin you could create another plugin that would return 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 function that will be called after jQuery gets user details from the Twitter servers.
P O S T ED B Y UZ B EK J O N A T 5: 29 A M 17 C O M M ENT S L A B ELS : A JA X , J Q UER Y, J S O N, P L UG I N

T U ES 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 behind was to lock all user interactions with the website while jQuery AJAX loads block contents and unlock when content is loaded. So I thought I would share the 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 page

overlay. You can style the overlaying layer using CSS. You can change font color, 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 the plugin at work:

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

35/73

20/01/2011

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 jQuery plugin adds. Do wnload uiLo ck jQuery plugin here.
P O S T ED B Y UZ B EK J O N A T 8: 26 A M 1 C O M M ENT S L A B ELS : A JA X , HO W T O , J Q UER Y, P L UG I N, T O O L S , W O R K A R O UND

FRI DAY, AP R IL 24, 2009

Twitter JSON/JSONP API URL
It is Friday and we don’t want to read long posts and tutorials. So today’s post is going to be short and sweet. I’ve been playing a lot with Twitter lately. I wrote some jQuery and javascript functions that get user details, etc. I will share it with you next week. But for today, I would like to share Twitter’s JSON and JSONP API URL. I am sharing it because it was hard to find it first. I actually wrote a jQuery plugin that gets Twitter user details using my previous post on cross site AJAX querying method. All Twitter API usage tutorials and articles I found on internet were based on RESTful non JSONP API, so I though I'll share Twitter JSON(P) API with 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 could replace it with a dynamic one that it has created. Update: Check o ut jQuery Twitter A PI plugin – jTw itter, that uses this Twitter A PI.
P O S T ED B Y UZ B EK J O N A T 1: 06 A M 2 C O M M ENT S L A B ELS : A JA X , J S O N, LI NK , R EFER ENC E, R ESO UR C E

T U ES 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 section or a block content on a page every x seconds. Some real life examples of this functionality are Twitter search results that come out when there are new tweets with search keyword or bit.ly real time link tracking that updates it’s charts every 5 seconds. It is clear without saying that we are going to update our page content using AJAX and of course we love AJAX in jQuery flavor. So key to this functionality is

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

36/73

20/01/2011

JQuery HowTo

JavaScript's built-in setInterval() function. It lets you to run some javascript function every X seconds. For example, the following code would pop alert box every 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 contents of #shotbox with new shouts.
P O S T ED B Y UZ B EK J O N A T 8: 08 A M 2 C O M M ENT S L A B ELS : A JA X , HO W T O , J Q UER Y, T I P , T UT O R I A L

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

Get geographical location (geolocation) by IP address 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 API returns the geographical location of the queried IP address with some additional information 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 location by 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 website that is specific to some location. For example, offering some advertising to US only 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

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

37/73

20/01/2011
$.getJSON(url, function(data){ if(data['status'] == 'ok'){ // Do something with the data $('#profile #ip') .append(data['IP']); $('#profile #country') .append(data['CountryName']); } });

JQuery HowTo

Here we are not specifying any IP address in the url variable that is why it is getting current user’s data.
P O S T ED B Y UZ B EK J O N A T 3: 12 A M 14 C O M M ENT S L A B ELS : A JA X , HO W T O , J A V A SC R I P T , J Q UER Y, R ES O UR C E, T I P , T O O LS , T UT O R I A L

Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, A P R I L 1 5 , 2 0 0 9

10

).

Shorten long URLs with jQuery & bit.ly service
I recently signed up to twitter and actively engaging with people who are interested in jQuery. Twitter is a great service and there are all kinds of developers who are sharing interesting links and resources. So it is some kind of interest 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 are lots of free URL shortening services, some are just for long URL shortening, some provide more features like real time click tracking, geostatistics and private URLs. The great thing about them is that they also provide you with an API. So I thought that there is a way we can make a use of them in our jQuery code. One of 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: login: apiKey: history: longUrl: }; '2.0.1', 'bitlyapidemo', 'R_0da49e0a9118ff35f52f629d2d71bf07', '0', ''

// 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 own applications.
P O S T ED B Y UZ B EK J O N A T 5: 50 A M 6 C O M M ENT S L A B ELS : A JA X , HO W T O , J A V A SC R I P T , J Q UER Y, R EFER ENC E, T I P , T O O LS , T UT O R I A L

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

38/73

20/01/2011
M O ND A Y, A P R I L 1 3 , 2 0 0 9

JQuery HowTo

Cross domain AJAX querying with jQuery
This post IS NOT about jQuery’s JSONP support. This post is about how to make AJAX queries to domains other then yours. Basically how to achieve cross domain scripting with jQuery. The technique will help you resolve the access to restricted uri denied" code: "1012 problem. UPDATE: If you want to get cro ss-domain RSS feeds, there is a better way to do that w ith 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 you and the rest of the world. This cross domain querying solution works because you actually loading the content from your own domain. You request the URL and the proxy script on your server actually loading the content from the internet and passing it over to you. I created a sample PHP proxy that I used to get related news RSS feed for one of 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 a jQuery 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 bad news is that not all web hosting companies allow fopen() to other domains, but enable it on request. My web server was very strict on security but the script above worked well on it.

For fetching RSS feeds, use a better solution with universal RSS2JSON co nverter.
P O S T ED B Y UZ B EK J O N A T 8: 05 A M 30 C O M M ENT S L A B ELS : A JA X , ER R O R , HO W T O , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND

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
http://jquery-howto.blogspot.com/ 39/73

20/01/2011

JQuery HowTo

with another one using jQuery
Swapping one image with another is probably one of the most used javascript techniques. Also Dreamweaver made “image replacement” even easier for non HTML/Javascript programmers by including this feature out of the box. One thing about Dreamweaver’s image swapping javascript is that it’s not the most beautiful javascript code. Well, as always with anything javascript related, jQuery is to the rescue. jQuery makes dynamic image swapping a peace of cake. All you need to do to replace your image with another one is to replace its src attribute. The browser 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 preload your images before you swap them.
P O S T ED B Y UZ B EK J O N A T 4: 18 A M 0 C O M M ENT S L A B ELS : A T T R I B UT ES , HO W T O , HT M L , JQ UER Y, M A NI P UL A T I O N, T I P , T UT O R I A L

FRI DAY, AP R IL 10, 2009

Select text in input box on user select or focus
A colleague of mine who is not very javascript or for that matter jQuery aware asked me to help him to do a little trick with jQuery. He needed to select the contents of the input box when user selects it (when onfocus event is fired basically). Selecting a text in your inputbox on focus is easy and actually 3 lines of jQuery code, but it add a nice usability touch to your site. This “select all” behavior is default in browser when you browse through form fields using TAB key, but when you click on to the input text field it does not behave like that.

jQuery code to select text inside an input field on user click 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 password fields, textarea fields, etc. Also we can add a little spice into our code and only select the contents of our text 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

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

40/73

20/01/2011
input fields :)
P O S T ED B Y UZ B EK J O N A T 7: 27 A M 1 C O M M ENT S L A B ELS : EV EN T S, HO W T O , HT M L , J Q UER Y, R EFER ENC E, T I P , W O R K A R O UND

JQuery HowTo

changed from the original one. This behavior would probably be more useful on

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 an example 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 your jQuery 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 it and 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: unreco gnized tag: $(".clazz").css("co lor", "red"); (Smarty_Co mpiler.class.php, line 455 ) in C:\PHP\smarty\libs\Smarty.class.php on line 1 092

The solution:
There are couple of things you can do about this problem: 1. Move your javascript (jQuery, Prototype, etc.) code into the external .js file. 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:

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

41/73

20/01/2011
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>
P O S T ED B Y UZ B EK J O N A T 12: 24 A M 6 C O M M ENT S L A B ELS : ER R O R , HO W T O , J Q UER Y, T I P , W O R K A R O UND

JQuery HowTo

Coupure de page insérée par AutoPager. Page (
M O ND A Y, A P R I L 6 , 2 0 0 9

11

).

Display loading GIF image while loading through AJAX
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 usually associated with using AJAX. No doubt using AJAX to load parts of your page and use more javascript effects, made easy by jQuery, is a great way to bring your website to life. But we should not forget about our users and the website usability. That is why it is a good practice to display something like text or image that informs users that the content is being loaded or processed. Now, let's see how can we display a loading image while requested content is being 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 we need to bind a click event to that button first and make AJAX request only after it is fired.
$("#btnLoad").click(function(){ // Make AJAX call $("#content").load("http://example.com"); });

The above code loads contents from http://example.com into the <div
id="content"> . While the page is being loaded we want to display our animated

GIF 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

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

42/73

20/01/2011
$("#content").load("http://example.com"); });

JQuery HowTo

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

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

and append your loaded data. If you have any question, please tweet me.
P O S T ED B Y UZ B EK J O N A T 5: 23 A M 17 C O M M ENT S L A B ELS : A JA X , HO W T O , HT M L , T I P , T UT O R I A L

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

Problems with jQuery mouseover / mouseout events
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 children elements and parent element has mouseover or mouseout event. Moving your mouse over children elements may fire mouseout event of their parent. This is caused by event bubbling / propagation and if you would like to have a quick solution just read the solution at the bottom of this post. If you would like to understand it in more details please search Google for event propagation.

The problem:
When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s
mouseover and/or mouseout event.

The solution:
The solution to this error is to use mouseenter and mouseleave events instead of
mouseover and mouseout .

The reason:
This solution works because mouseover and mouseout events do not bubble from child to parent element.
P O S T ED B Y UZ B EK J O N A T 4: 56 A M 24 C O M M ENT S L A B ELS : EV EN T S, J Q UER Y, T I P , W O R K A R O UND

W ED NES D A Y, A P R I L 1 , 2 0 0 9

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem
Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page. This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below. The solution:
// Reload mypage.html every 5 seconds var refresh = setInterval(function()

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

43/73

20/01/2011
{ // Minimized code, suggested by Kovacs $('#mydiv').load("mypage.htm?" + 1*new Date() );

JQuery HowTo

}, 5000);
P O S T ED B Y UZ B EK J O N A T 3: 29 A M 11 C O M M ENT S L A B ELS : A JA X , ER R O R , HO W T O , I NS I G HT S , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND

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

Use different CSS rules / styles in JavaScript or jQuery enabled browsers
This is a simple yet very useful and powerful technique. Using different CSS rules in JavaScript or jQuery enabled browsers lets you customize your website style for JS enabled and disabled browsers using only CSS. Thus you separate concerns of styling and business logic into CSS and javascript. This lets you concentrate 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 using javascript/jquery to specify that javascript/jQuery is available. Then define two rules 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 enabled browser you might ask. Consider you have a drop-down menu on your website’s sidebar and you would like to use jQuery/Javascript to make it drop down on mouse 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 on his/her browsers. Similar to previous example, we can use difference CSS style for jQuery enabled browsers.
if(jQuery){ jQuery("body").addClass("jq"); }

And in your CSS file:
.someClass{ display:block; } .jq .someClass{ display:none; }
P O S T ED B Y UZ B EK J O N A T 7: 18 A M 4 C O M M ENT S L A B ELS : CSS , HO W T O , HT M L , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND

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 I could 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 you are interested in jQuery than you can follow people who share tweets about

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

44/73

20/01/2011
jQuery HowTo accounts.

JQuery HowTo

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

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.
P O S T ED B Y UZ B EK J O N A T 10: 34 P M L A B ELS : NEW S 0 C O M M ENT S

Coupure de page insérée par AutoPager. Page (
T H UR S D A Y, M A R C H 2 6 , 2 0 0 9

12

).

Check if jQuery plugin is loaded
The previous post checked if jQuery is loaded, now it is time to check if particular jQuery plugin is loaded. Checking if plugin exists or if plugin has been already loaded 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 created as an additional namespace within jQuery namespace. All you have to do to check 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 }
P O S T ED B Y UZ B EK J O N A T 4: 06 A M 7 C O M M ENT S L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, P L UG I N , T I P , W O R K A R O UND

W ED NES 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 who were interested in adding and using jQuery on their Blogger.com (Blogspot.com) accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. All you 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 host it 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)
P O S T ED B Y UZ B EK J O N A T 5: 19 A M 5 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, T I P , W O R K A R O UND

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

45/73

20/01/2011
T U ES D A Y, M A R C H 2 4 , 2 0 0 9

JQuery HowTo

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 programming environment is JavaScript and the object we are checking for existence is
jQuery() / $() function.

This method is no t limited to jQuery o nly, you c an chec k for any other variable or functio n in your javascript.

Anyway, jQuery() or $() functions will only be defined if they are already loaded into 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 way to check for jQuery library being loaded. In case you are not using any other javascript 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.
P O S T ED B Y UZ B EK J O N A T 7: 07 A M 4 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, T ES T , T I P , W O R K A R O UND

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

Dynamically creating input box/checkbox/radio button... does not work in Internet Explorer (IE)
While working on some project, trying to create a checkbox and radio button dynamically using jQuery I came across a problem. Mozilla Firefox, Opera and Safari were creating and rendering my new checkboxes just fine, but Internet Explorer (IE6, IE7) did not create them. I spend half a day trying to figure out what 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 form element 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 set with 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 checkboxes and radio buttons are not displayed/created.

Solution:
To solve the problem you need to create an input field with type attribute already defined.

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

46/73

20/01/2011

JQuery HowTo

P O S T ED B Y UZ B EK J O N A T 7: 59 A M 5 C O M M ENT S L A B ELS : DO M , ER R O R , HO W T O , HT M L , J Q UER Y, M A NI P ULA T I O N, T I P , W O R K A R O UND

FRI DAY, M ARC H 20, 2009

jQuery UI 1.7.1 released
The first maintenance release for jQuery UI 1.7 has been released. You can download jQuery UI 1.7.1 from the following links: Uncompressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.js Compressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jqueryui.min.js
P O S T ED B Y UZ B EK J O N A T 5: 44 A M L A B ELS : JQ UER Y UI , NEW S 0 C O M M ENT S

Coupure de page insérée par AutoPager. Page (
M O ND A Y, M A R C H 1 6 , 2 0 0 9

13

).

Only the last element is bound/inserted/etc. in your javascript code’s “for” loop
There is a common problem when you use javascript for loop to bind an event function 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 still will 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 called immediately 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 last arrays/elements/etc. attribute value (id/class/etc.).
P O S T ED B Y UZ B EK J O N A T 6: 03 A M 5 C O M M ENT S L A B ELS : EV EN T S, HO W T O , I NS I G HT S , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND

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

Convert javascript objects into arrays for better performance
jQuery Howto blog has many posts on your javascript and jQuery code performance. If you have read the last performance post named “5 easy tips on how to improve code performance with huge data sets in jQuery” then you

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

47/73

20/01/2011
performance.

JQuery HowTo

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

The only problem is that jQuery returns an object not an array when you select elements. Consider you have an object with lots of entries and you have to perform some manipulations that are available in javascript array such as
reverse , sort , join , etc. Using built in methods is much faster then those you

might write yourself. So the best thing would be converting your objects to arrays and 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);
P O S T ED B Y UZ B EK J O N A T 10: 29 P M 3 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, M A NI P UL A T I O N, P ER FO R M A NC E, T I P , W O R K A R O UND

FRI DAY, FEB RUARY 27, 2009

Preload images with jQuery
Web2.0 came with AJAX and AJAX came with its own requirements and standards for web application developers. Now web applications are more like desktop applications with a lot of options, dialogs and more. If you have developed AJAX application with different user controls you surely loaded resources such images, other javascript files on demand. This helps you keep your application lightweight and makes its load time faster. jQuery makes creation and loading DOM elements (in our case images) very easy. 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 the image element would tell the user browser to load that image. Thus preloading the image. Next you should insert your DOM element into the DOM tree using one of the many jQuery DOM manipulation methods. Here are some examples of how you could insert preloaded image into your website:
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 image into 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.
P O S T ED B Y UZ B EK J O N A T 6: 27 A M 16 C O M M ENT S L A B ELS : EV EN T S, HO W T O , J Q UER Y, M A NI P UL A T I O N, T I P , W O R K A R O UND

W ED NES D A Y, F EB R UA R Y 2 5 , 2 0 0 9

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

48/73

20/01/2011

JQuery HowTo

How to add more items to the existing jQuery selection
There are occasions when you have already selected elements and need to add more items to it. Imagine you have selected different items and have jQuery selection object. For example:
var elms = $('#elem, .items');

Now, you need to add more new items (DOM nodes) to your section. Let’s say you want to add .otherItems to your elms selection. You could achieve it by using 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 jQuery object/selection to the existing selection”. Anyway, it’s just wording :)
P O S T ED B Y UZ B EK J O N A T 6: 12 A M 0 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, S ELEC T O R S, T I P , W O R K A R O UND

T U ES D A Y, F EB 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 have it. In such cases you can use the following javascript code or the bookmarklet that would insert jQuery into the page’s DOM on the fly. Thus making jQuery available for use in Firebug.

Load jQuery to Firebug
Here are two options to jQuerify any page. The code is taken from a jQuerify javascript 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 bookmarks toolbar: Load jQuery – When you click on this link it will load jQuery from Google’s server and make it available in Mozilla add-on Firebug.
P O S T ED B Y UZ B EK J O N A T 6: 13 A M 1 C O M M ENT S L A B ELS : FI R EB UG , HO W T O , I NS I G HT S , JQ UER Y, P L UG I N, T I P , T O O L S , W O R K A R O UND

Coupure de page insérée par AutoPager. Page (
M O ND A Y, F EB R UA R Y 2 3 , 2 0 0 9

14

).

jQuery 1.3.2 Released
It seems that the jQuery’s new maintenance release 1.3.2 has not got enough coverage on other sites and thus a lot of developers still don’t know of it’s release. 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;

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

49/73

20/01/2011
read release notes for more information on changes.
P O S T ED B Y UZ B EK J O N A T 11: 37 P M 0 C O M M ENT S L A B ELS : JQ UER Y, NEW S, P ER FO R M A NC E

JQuery HowTo

and now selectors return elements in their document appearance order;

FRI DAY, FEB RUARY 20, 2009

Add table row using jQuery and JavaScript
I noticed that there are a lot of developers who need to dynamically add a new table row to the bottom of their tables. I wrote a little javascript function that takes your jQuery selection of tables and dynamically adds a table row at the bottom 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'));
P O S T ED B Y UZ B EK J O N A T 4: 35 A M 2 C O M M ENT S L A B ELS : DO M , HO W T O , HT M L , JA V A S C R I P T , JQ UER Y, M A NI P UL A T I O N, T I P , W O R K A R O UND

W ED NES D A Y, F EB R UA R Y 1 8 , 2 0 0 9

How to use YUICompressor to compress your javascript code?
Since writing on this blog I posted two jQuery plugins and I needed to compress my js files. So as jQuery documentation suggests I used YUICompressor. YUICompressor is javascript and CSS file/code compressor written in Java language. 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 last parameter (in our case minimized.file.js).

Links:
1. Download YUICompressor 2. Download JRE (required to run java applications) 3. Online version of YUICompressor
P O S T ED B Y UZ B EK J O N A T 3: 58 A M 3 C O M M ENT S

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

50/73

20/01/2011

JQuery HowTo

L A B ELS : CSS , HO W T O , I NS I G HT S, J A V A S C R I P T , J Q UER Y, L I NK , R EFER ENC E, R ES O UR C E, T I P , T O O LS

M O ND A Y, F EB R UA R Y 1 6 , 2 0 0 9

Font cleartype problems with fadeIn() and fadeOut() 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 the
filter 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 its job. In other words, as a function callback. Otherwise, fadeIn()/fadeOut() functions would change the opacity of the element, which in turn would cause the
filter attribute to be attached yet again. So, remove the attribute in function

callback like this:
$('#message').fadeIn(function(){ this.style.removeAttribute("filter"); });
P O S T ED B Y UZ B EK J O N A T 6: 56 A M 23 C O M M ENT S L A B ELS : A NI M A T I O N, ER R O R , HO W T O , HT M L, I NS I G HT S, J A V A S C R I P T , J Q UER Y, M A NI P UL A T I O N, R EFER ENCE, T I P , W O R K A R O UND

S A T UR D A Y, F EB 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 jqueryhowto.blogspot.com with jQuery and javascript code. I am using lightweight Google Code Prettify to highlight my code. Here is an example of the new highlighter:
function JavascriptFunction() { // Comment example var myVariable;

var privateMethod = function(){ };

return myVariable; }

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

51/73

20/01/2011
// jQuery code sample $.extend({ myNamespaced: function(myArg){ return 'namespaced.' + myArg; } }); $.myNamespaced('A'); // Another comment
P O S T ED B Y UZ B EK J O N A T 3: 42 A M L A B ELS : NEW S 3 C O M M ENT S

JQuery HowTo

Coupure de page insérée par AutoPager. Page (
FRI DAY, FEB RUARY 13, 2009

15

).

Automatically add table row count column to your tables with jQuery rowCount plugin
Some time ago I wrote a javascript code that automatically adds table row count column to your tables. And now I thought I would compile a jQuery plugin and submit it to the jQuery plugins repository. Y ou can dow nlo ad jQuery ro wCo unt plugin.

The script takes into consideration your table header's row and column spans.

Features:
Gracefully degrade for those browsers that do not support javascript Lets you keep your HTML mark up clean Make 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 columns automatically added.

P O S T ED B Y UZ B EK J O N A T 3: 26 A M 2 C O M M ENT S L A B ELS : HO W T O , HT M L, J Q UER Y, M A NI P UL A T I O N, P L UG I N

T H UR S D A Y, F EB 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 Google makes it easy to use its content on your own site. You can embed a YouTube video on your own site or query YouTube API (if you have a developer key). But

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

52/73

20/01/2011

JQuery HowTo

what if you don't want to embed a flash video player and you only need an image of the video. The following function returns a YouTube video's thumbnail URL. Nothing more, nothing less. Update: No w available as jQuery Y o uTube 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 a path to the video image. The second function argument is optional. You can specify 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 actio n on jQuery Y ouTube demo page.
P O S T ED B Y UZ B EK J O N A T 3: 59 A M 22 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , R EFER ENC E, T I P , W O R K A R O UND

W ED NES D A Y, F EB R UA R Y 1 1 , 2 0 0 9

How to set custom rules in jQuery Validation plugin for fields that have a period "." in their names
We all love and use jQuery Validation plugin. For basic forms it does a great job and works flawlessly 80% of the time. But we all work on different kinds of projects and validation requirements change project to project. jQuery Validation is a very flexible plugin and provides a way to easily define your own validation rules. You can read more about jQuery Validation plugin and custom validation rules here. It is quite straight forward. Anyway, I was working on a project that requires the use of custom rules and I had no control over the generated HTML code and used CSS selectors. So I had to work with CSS classes that had period "." symbol in their names. My first attempt failed. Here is the code that failed. Pay attention to the selector name with the (.) in it's name.
rules: { user.email: { required: true, email: true } }

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

53/73

20/01/2011

JQuery HowTo

It is common in Java programming world that your form fields have periods (.) in their names and this is an example of that. So to solve the problem all you have 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...
P O S T ED B Y UZ B EK J O N A T 7: 11 A M 1 C O M M ENT S L A B ELS : ER R O R , HO W T O , I NS I G HT S , JQ UER Y, P L UG I N, T I P , W O R K A R O UND

M O ND A Y, F EB R UA R Y 9 , 2 0 0 9

5 easy tips on how to improve code performance with huge data sets in jQuery
Sitting on jQuery's support mailing list I noticed that developers use jQuery with huge data sets and their code becomes very slow. Examples would be generating very long tables with a lot of rows using AJAX to get JSON data. Or iterating through a long (very long) list of data, etc. So I compiled a list of 5 easy tips on how to improve your code performance while 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 functions that were built to add an abstraction layer. In case you are looping through an object that you have received as JSON, I highly recommend you rewrite 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 significantly improve 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. Instead store it in a variable as text and append it to the DOM after your loop finishes 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, surround them with a parent element for better performance. When you have a lot of elements to insert into the DOM tree it takes time to add them all. Somehow adding one element with 1000 children is faster than adding 1000 children separately. You can search this site for performance tests that prove it. So, to improve our previous example's performance let's cover <tr> 's with
<tbody> tag like this:

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

54/73

20/01/2011
var tmp = '<tbody>'; for (var i=0; i<=rows.length; i++) { tmp += '<tr><td>'+rows[i]+'</td></tr>'; } tmp += '</tbody>'; $('#myTable').append(tmp);

JQuery HowTo

4. Don't use string concatenation, instead use array's join() method for 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 list looping and concatenation functions. This will make sure that page does not freeze while it loops through the long list of data and lets users to work with your page meanwhile. It was well mentioned in comments that setTimeout() function should be used to split your code processing into little chunks so your browser does not freeze up like this:

function myFunk(data){

// do processing

if(!has_finished) setTimeout("myFunk()", 100); }
P O S T ED B Y UZ B EK J O N A T 7: 20 A M 16 C O M M ENT S L A B ELS : DO M , HO W T O , I NS I G HT S , J A V A SC R I P T , J Q UER Y, M A NI P ULA T I O N, P ER FO R M A NCE, R ES O UR CE, T I P , W O R K A R O UND

S A T UR D A Y, F EB 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 is working with. This maybe useful in you jQuery plugins, so your code can utilize the jQuery version specific code or maybe your code is running in some environment 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;
P O S T ED B Y UZ B EK J O N A T 12: 33 A M 4 C O M M ENT S L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, R EFER ENC E, T I P , W O R K A R O UND

Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, F EB R UA R Y 4 , 2 0 0 9

16

).

How to disable all jQuery animations at once
Yesterday I came across jQuery.fx.off setting in jQuery documentation. It

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

55/73

20/01/2011
true .

JQuery HowTo

disables all jQuery animations effective immediately when you set it's value to

Consider this code:
jQuery.fx.off = true;

$("input").click(function(){ $("div").toggle("slow"); });

Your div will be showed/hidden immediately without animation. One of the reasons (as documentation mentions) to disable animations would be "slow" environments.
P O S T ED B Y UZ B EK J O N A T 4: 29 A M 1 C O M M ENT S L A B ELS : A NI M A T I O N, EV ENT S, HO W T O , J Q UER Y, P ER FO R M A NC E, R EFER ENC E, T I P

T U ES D A Y, F EB R U A R Y 3 , 2 0 0 9

Why should I include all my CSS files before jQuery?
The simple answer is: "Because you have to". Since jQuery version 1.3 jQuery does 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 about waiting for all stylesheets to be loaded. Instead all CSS files should be included befo re the scripts on the page.

This takes us to one more of our jQuery tips. TIP:

Include all your CSS files before jQuery file.
P O S T ED B Y UZ B EK J O N A T 2: 25 A M 4 C O M M ENT S L A B ELS : I NS I G HT S , JQ UER Y, R EFER ENC E, T I P

M O ND A Y, F EB R UA R Y 2 , 2 0 0 9

How to get full html string including the selected element 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 this

HTML 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 <div
id="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

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

56/73

20/01/2011
would not need to do all the DOM manipulations.

JQuery HowTo

P O S T ED B Y UZ B EK J O N A T 3: 59 A M 13 C O M M ENT S L A B ELS : DO M , HO W T O , JQ UER Y, M A NI P UL A T I O N, S EL EC T O R S , T I P , W O R K A R O UND

FR I DA Y, J A NUA R Y 30, 2009

How to create a rounded corner box plugin with jQuery
Recently, we have redesigned one of our projects. The task was to make the web application to look and act more like Web2.0 app. New design looked great and surely it had lot's of rounded corners. Y ou can dow nlo ad jQuery Rounded Corners plugin.

First, rounded corners were done using CSS, but it got our code cluttered and it introduced a lot of unnecessary HTML markup. Since we had full control of our target audience's browsers and we were sure that they had JavaScript enabled browser we chose jQuery to do all the dirty work. All we have to do to define a box/table/anything to be in a rounded box is to give it a class "boxed" and the rest 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;}
P O S T ED B Y UZ B EK J O N A T 11: 25 P M L A B ELS : HO W T O , J Q UER Y, P L UG I N 6 C O M M ENT S

W ED NES 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 and then made a plugin out of it. We could further improve our plug-in by providing an option to let plug-in users to overwrite default setting. For example plugin users could provide a CSS class to set to the added column or 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:

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

57/73

20/01/2011
$.fn.addCount = function(options) { // set up default options var defaults = { colName: colWidth: addCssClass: colClass: }; '#', 100, true, 'mycolumn',

JQuery HowTo

// 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); This line merges options and defaults variables adding missing properties in
options variable from defaults variable.

Here is a great example from documentation page of jQuery.extend() that gives 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);
P O S T ED B Y UZ B EK J O N A T 3: 32 A M 0 C O M M ENT S L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, P L UG I N , T I P

Coupure de page insérée par AutoPager. Page (
M O ND A Y, J A NU A R Y 2 6 , 2 0 0 9

17

).

Namespace your JavaScript function and variable with jQuery
We all know that global variable are evil. Namespacing your variables and methods is now considered a good practice and shows your awareness about the trends. Anyway, I thought how can I namespace my variables and methods in 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 already declared functions with the same name. This is great, but to access my functions or variables I have to call jQuery() . The code still looks like chaining not namespacing. To declare your variables or functions in jQuery namespace you can extend the core jQuery object itself using jQuery.extend() rather than
jQuery.fn.extend() .

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

58/73

20/01/2011
$.extend({ myNamespaced: function(myArg){ return 'namespaced.' + myArg; } }); jQuery.myNamespaced('A'); $.myNamespaced('A'); // Shorthand // Outputs: namespaced.A

JQuery HowTo

As you can see, now I can call my functions and properties without parenthesis after jQuery object. Now my functions have a jQuery namespace and will not conflict with other functions that might have the same name. TIP:

Use $.extend({}) to namespace your fields and methods.
P O S T ED B Y UZ B EK J O N A T 6: 18 A M 8 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, O O P , T I P

FR I DA Y, J A NUA R Y 23, 2009

Dynamically adding table row count number using JavaScript and jQuery
Now available as a ro wCount jQuery plugin.

Recently on jQuery mailing list a user asked how he/she could add a row count in 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 it has only one row in its header. That is why I took into the account the possibility of row spans and multi line rows in header and rewrote the code. Then made a plugin 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>'); }); } });

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

59/73

20/01/2011
} }); })(jQuery);

JQuery HowTo

To apply it to your tables use this code:
$('table').addCount(); $('.some-table-class').addCount(); $('#some-table-id').addCount();
P O S T ED B Y UZ B EK J O N A T 11: 30 P M 5 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, M A NI P UL A T I O N, P L UG I N, T I P

W ED NES D A Y, J A N UA R Y 2 1 , 2 0 0 9

Object-Oriented JavaScript, how to achieve public properties/fields
Recently I posted my findings about private fields in JavaScript. So this is a continuation 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 accessible from 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 for private and public methods. The idea behind is the same. To make a method public you need to define it in your return object and if you want to make it private you 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(); },

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

60/73

20/01/2011
getName: function() { return name; } }; } var user = new User(); user.setName("My Name"); user.getName(); // My Name Changed

JQuery HowTo

As you can see, privateMethod and name are declared outside the return object and thus they are made private. Variables declared inside the return object are public and accessible using dot notation.
P O S T ED B Y UZ B EK J O N A T 6: 34 A M 6 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , O O P , T I P

FR I DA Y, J A NUA R Y 16, 2009

jQuery 1.2.6 and jQuery 1.3 class selector performance benchmark
Reading about the jQuery 1.3's new selector engine Sizzle and its speed improvements I thought I would do a performance comparison between jQuery 1.2.6 and jQuery 1.3. I was prepared for something good, but the test results blew 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

/** * jQuery 1.3

1235 ms 1326 ms 1342 ms ======= 1301 ms

54 ms 52 ms 53 ms ======= 53 ms

*/

*/

As you can see the new selector engine is freakishly fast :) Actually with this specific test it is 25 times fast. Taking into the consideration that class selection is one of the most used selectors, we can assume that our code will work considerably faster. NOTE: I have performed the same tests with selection with id's. The result were exactly the same (9 ms). Taking into the consideration that both versions of jQuery use browser's built in getElementById() function for ID selections, there is not much one can do to beat that.
P O S T ED B Y UZ B EK J O N A T 5: 18 A M 4 C O M M ENT S L A B ELS : JQ UER Y, P ER FO R M A NCE, S ELEC T O R S , T EST

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 into jQuery.Event object. As it says in the documentation: " The event object is

guaranteed to be passed to the event handler (no checks for window.event required)."
Here is an jQuery.Event object ove rview :

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

61/73

20/01/2011
Attributes 1. event.type 2. event.target 3. event.relatedTarget 4. event.currentTarget 5. event.pageX/Y 6. event.result 7. event.timeStamp Methods 1. event.preventDefault() 2. event.isDefaultPrevented() 3. event.stopPropagation() 4. event.isPropagationStopped() 5. event.stopImmediatePropagation() 6. event.isImmediatePropagationStopped()
Now , how to w ork w ith jQuery.Event object?

JQuery HowTo

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. So your 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 create new 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 of fun things with them. Example: event.result , event.relatedTarget.
P O S T ED B Y UZ B EK J O N A T 7: 14 A M 2 C O M M ENT S L A B ELS : EV EN T S, HO W T O , I NS I G HT S , J Q UER Y, R EFER ENC E

Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, J A N UA R Y 1 4 , 2 0 0 9

18

).

jQuery 1.3 has been released!
Long awaited jQuery 1.3 has just been released. You can read about it on jQuery blog and release notes. Notable changes: new blazingly fast selectors engine (Sizzle) new jQuery.Event object that is available in your event functions faster HTML injection (~6x faster)

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

62/73

20/01/2011
.hide() and .show() are now much faster (~2.5x faster) [@attr] syntax deprecated, use [attr] and many many more. Please read release notes.
P O S T ED B Y UZ B EK J O N A T 7: 04 A M L A B ELS : JQ UER Y, NEW S 0 C O M M ENT S

JQuery HowTo

Pack and minimize your JavaScript code size
In pursue for my JavaScript code performance and some questions on jQuery mailing list I looked for and eventually came across some of the JavaScript code packers. 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 and JavaScript code.
P O S T ED B Y UZ B EK J O N A T 6: 05 A M 5 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, L I NK , P ER FO R M A NC E, R ESO UR C E, T I P

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's supposed to do. After killing half an hour on trying to figure out what is the problem you either give up and decide to rewrite or leave it for later. Later looking at 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.

P O S T ED B Y UZ B EK J O N A T 4: 37 A M 0 C O M M ENT S L A B ELS : ER R O R , HO W T O , J A V A S C R I P T , LI NK , R ES O UR C E, T ES T

FR I DA Y, J A NUA R Y 9, 2009

jQuery and HTML image maps
Most of us don't even use image maps anymore. But occasionally, mostly when freelancing, you will need to work with the pages that were created in mid 90's and image maps where pop stars in that era. Anyway to refresh your memory here 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 like this:
$('area').click(function() { var url = $(this).attr('href'); var coords = $(this).attr('coords').split(',');

// Your code here

// To prevent default action return false;

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

63/73

20/01/2011
});

JQuery HowTo

This is all that I have on jQuery and image maps.
P O S T ED B Y UZ B EK J O N A T 5: 14 A M 5 C O M M ENT S L A B ELS : HO W T O , HT M L, J Q UER Y, R EFER ENC E, S EL EC T O R S , T I P

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. I had 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 no jQuery selector but you can use selectors that exist to achieve this goal. The innermost 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");
P O S T ED B Y UZ B EK J O N A T 3: 01 A M 2 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, S ELEC T O R S, T I P

Coupure de page insérée par AutoPager. Page (
W ED NES D A Y, J A N UA R Y 7 , 2 0 0 9

19

).

Object-Oriented JavaScript, how to achieve private properties/fields
The very basic of Object-Oriented Programming (OOP) is private fields and public methods (not considering features like polymorphism, inheritance, etc). So how to achieve this very basic of OOP in JavaScript. It turns out to be easy. Here is how to have private fields in your custom JavaScript functions/classes and using methods 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 this template you can have as many private fields and public methods as you want.
P O S T ED B Y UZ B EK J O N A T 6: 51 A M 2 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , O O P , R EFER ENC E, T I P

T U ES D A Y, J A NU A R Y 6 , 2 0 0 9

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

64/73

20/01/2011

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 custom functions. To extend you write $.fn.myFunction and then your function. It was interesting 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 discovery of the century but it gives you some understanding of how jQuery's plug-in system works and its insights.
P O S T ED B Y UZ B EK J O N A T 2: 28 A M 0 C O M M ENT S L A B ELS : I NS I G HT S , JQ UER Y, P L UG I N, R EFER ENC E

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 your jQuery code performance. You should use ID selections whenever you can. Because jQuery uses browser's native getElementById() function which is much faster. Now back to JavaScript code performance testing. I have an unordered list with 1000 items. First test will have list items with class attributes and the second list 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 256 times (8204/32).
P O S T ED B Y UZ B EK J O N A T 3: 16 A M 0 C O M M ENT S L A B ELS : JQ UER Y, P ER FO R M A NCE, S ELEC T O R S , T I P

T U ES D A Y, D EC EM B ER 3 0 , 2 0 0 8

How to disable/enable an element with jQuery
Sometimes you need to disable or enable some elements in your document and jQuery makes this task easy. All you have to do is to set disabled attribute to "disabled ".
Exam ple:

// To disable $('.someElement').attr('disabled', 'disabled');

In order to enable any disabled element you need to set the disabled attribute to 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 your website using jQuery. You can see this code in action in real life example of

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

65/73

20/01/2011
Disabling submit button on form submission post.

JQuery HowTo

P O S T ED B Y UZ B EK J O N A T 1: 58 A M 15 C O M M ENT S L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , J Q UER Y, M A NI P ULA T I O N, R EFER ENC E, T I P

M O ND A Y, D EC E M B ER 2 9 , 2 0 0 8

Caching in jQuery
What is great about jQuery is its simplicity in selecting elements. We all use it here and there, basically everywhere. This simplicity comes with its drawbacks. jQuery traverses through all elements every time we use selectors. So to boost up your jQuery application you should always cache your selections to some variable (if you find yourself using the same selection more than once). In case you are not selecting an element more than once you should not cache your selection by assigning it to some variable.
Here is an exam ple:

var cached = $('.someElement'); cached.addClass('cached-element');

Here are the perform ance 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.
P O S T ED B Y UZ B EK J O N A T 9: 47 P M 7 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, P ER FO R M A NC E, S EL EC T O R S , T I P

Coupure de page insérée par AutoPager. Page (
M O ND A Y, D EC E M B ER 2 9 , 2 0 0 8

20

).

How to check if checkbox is checked using jQuery
Note: If you are new to jQuery , you might find our short jQuery beginner tuto rials useful.

While working on my previous project I needed a way to check if the certain checkbox is checked or not. jQuery is a great library but I had a hard time identifying if any particular checkbox was checked. So here is the way to do just that. 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 }

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

66/73

20/01/2011
); // Third way == UPDATE jQuery 1.3 $("input[type=checkbox][checked]").each( function() { // Insert code here } );

JQuery HowTo

// 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 was checked or false if it is not checked. The third method iterates though all checkboxes with checked attribute defined and performs some action.

See the latest jQuery tips. They are sho rt, very sho rt!

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.
P O S T ED B Y UZ B EK J O N A T 4: 18 A M 19 C O M M ENT S L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , HT M L , J Q UER Y, R EFER ENC E, T I P

FRI DAY, DECEM B ER 26, 2008

How to test JavaScript code performance
Sometimes after all day long coding your code becomes not so effective and your code (usually interface related) becomes slow. You have done so many changes and don't exactly know what slowing it down. In cases like this (and of course, plenty other cases) you can test your JavaScript code performance. First of all, you need Firefox browser and Firebug web developers life saver plugin. 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 the Firebug console. Console also has one handy method for tracking time in milliseconds.
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 can be any name for your timer. Don't forget to end your timer using the same name for timeEnd() .
P O S T ED B Y UZ B EK J O N A T 4: 26 A M 0 C O M M ENT S L A B ELS : FI R EB UG , HO W T O , JA V A S C R I P T , P ER FO R M A NC E, R EFER ENC E, T ES T , T I P

T H UR S D A Y, D EC EM B ER 2 5 , 2 0 0 8

Everything has characteristics of an Array in JavaScript
The title maybe a little misleading. So don’t confuse Arrays with Object in JavaScript! They have common and non-common methods. You can use jQuery built-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 with you. So every object I tried to use had capabilities of array. I could refer to object/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";

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

67/73

20/01/2011
}

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 use prototype .
P O S T ED B Y UZ B EK J O N A T 5: 28 A M 0 C O M M ENT S L A B ELS : HO W T O , J A V A S CR I P T , T I P

T U ES D A Y, D EC EM B ER 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 system and a shorthand for that. If you look into them closely they are actually the same thing. The only difference being that the code in first one is wrapped in this anonymous JavaScript function:
(function ($) { // code goes here })(jQuery)

Little research shows that this allows the use of $ within this function without conflicting with other JavaScript libraries who are using it. Basically, since we are setting $ as a parameter, $ will overwrite any globally defined variables/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 other javascript libraries that might have $ variable/function. Also if you notice, all jQuery 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);
P O S T ED B Y UZ B EK J O N A T 11: 40 P M 2 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, R EFER ENC E, T I P

M O ND A Y, D EC E M B ER 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 own functions. Since then I came across even smaller code snippet on how to add your own custom functions, in other words how to create plugins for jQuery. So without further ado:
$.fn.myFunction = function() { return $(this).addClass('changed'); }

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

68/73

20/01/2011
And now, use it like this:
$('.changePlease').myFunction();

JQuery HowTo

And that is all there is :)
P O S T ED B Y UZ B EK J O N A T 9: 55 P M 7 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, P L UG I N, R EFER ENC E, T I P

Coupure de page insérée par AutoPager. Page (
M O ND A Y, D EC E M B ER 2 2 , 2 0 0 8

21

).

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 are already minimized, gzipped and if your visitors have already visited some site that loaded jQuery from Google Code then it already be on user's machine. So there is nothing to load. UPDATE: Y ou can also use jQuery hosted by Microsoft CDN servers.

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 you can 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"

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

69/73

20/01/2011
type="text/javascript"></script>

JQuery HowTo

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
P O S T ED B Y UZ B EK J O N A T 9: 43 P M 8 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, L I NK , P ER FO R M A N C E, R EFER ENC E, T I P

M O ND A Y, D EC E M B ER 1 5 , 2 0 0 8

How to create a jQuery plugin, extending jQuery the easy way
I have read a great book on jQuery Learning JQuery . I skimmed through the chapter on extending jQuery and creating its plugins. It is quite easy. All you have 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 from your newly created methods.
P O S T ED B Y UZ B EK J O N A T 3: 19 A M 2 C O M M ENT S L A B ELS : HO W T O , J Q UER Y, P L UG I N, R EFER ENC E, T I P

S UN D A Y, D EC EM B ER 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() . We also all use jQuery's event bindings. When you use them both, problems such as your event bindings like click() are not bided to your new AJAX loaded elements. To solve this problem you need to bind events to your newly loaded elements. NOTE:

Make sure you don't bind the same event to the elements with this event already bound.
TIP:

You should somehow separate newly created elements and then bind event in callback 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 querying AJAX update content every X seconds Display loading GIF image while loading through AJAX

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

70/73

20/01/2011
Update: A dded a demo page that show s how to bind events to A JA X lo aded elements here.
P O S T ED B Y UZ B EK J O N A T 1: 03 A M 7 C O M M ENT S L A B ELS : A JA X , EV ENT S , HO W T O , JQ UER Y, T I P , W O R K A R O UND

JQuery HowTo

S A T UR D A Y, D EC EM B ER 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. The size 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 the same value as .length property but it is slightly slower, however the difference is insanely small. So you can use .length or .size() depending on your choice.
// Example usage for .size() $('.someClass').size();
P O S T ED B Y UZ B EK J O N A T 1: 40 A M 2 C O M M ENT S L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , I NSI G HT S , J Q UER Y, R EFER ENC E, S EL ECT O R S , T I P

Access to restricted URI denied" code: "1012
I was working on the interface for our catalogue/directory structure. We use great JavaScript library jQuery as our JS framework. While working on page AJAX requests 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 local resource. In other words, 'Access to restricted URI denied" code: "1012' error occurs when javascript tries to load a file from my hard drive. The file type let it be CSS, HTML, javascript does not matter.

Reason:
1. The reason for the error is Firefox's security model that does not allow retrieving/accessing localhost resources. 2. Also Firefox does not allow accessing resources from other domains (NOTE: www.example.com and example.com are considered two different domains as well).

Solution:
1. So, to solve this problem you need to deploy your files to your web server or run one locally. You can run XAMPP or lightweight Denwer (similar to XAMPP, but it is in Russian). 2. To access resources from other domains you can put a simple proxy script, as it is described in this “Cross domain AJAX scripting” post.
P O S T ED B Y UZ B EK J O N A T 1: 17 A M 23 C O M M ENT S L A B ELS : A JA X , ER R O R , FI R EB UG , JA V A S C R I P T , R EFER ENC E, W O R K A R O UND

Coupure de page insérée par AutoPager. Page (
S A T UR D A Y, N O V EM B ER 1 , 2 0 0 8

22

).

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

71/73

20/01/2011

JQuery HowTo

Set HTML tag’s / element’s attribute
In our previous post about “How to get an element’s / tag’s attribute” I described how to get element’s attribute. In this post I would like to show you how to set any HTML tag’s or element’s attributes. Don’t forget, jQuery can set any attributes 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 you can 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?!
P O S T ED B Y UZ B EK J O N A T 7: 31 A M 3 C O M M ENT S L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , J Q UER Y, M A NI P ULA T I O N

Getting HTML tag attribute of an element using jQuery
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’s

attribute. Example: Consider we have the following HTML tags on our page with corresponding attributes:
<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 use the 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 to
Google .

NOTE: If your jQuery selection returns more than once element, .attr() function would return only the first element’s attribute.
P O S T ED B Y UZ B EK J O N A T 7: 11 A M 2 C O M M ENT S L A B ELS : A T T R I B UT ES , HO W T O , JQ UER Y

Home

Older Posts »

Subscribe to: Posts (Atom)

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

72/73

20/01/2011
© jQuery How to.

JQuery HowTo
jQuery is a javascript framew ork or javascript library that abstracts common javascript tasks and gives developers tools 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.

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

73/73

Sign up to vote on this title
UsefulNot useful